import type { FC, ReactNode } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import {
  LayoutDashboard,
  Calendar,
  Users,
  Stethoscope,
  Briefcase,
  Package,
  Wallet,
  CreditCard,
  ShoppingCart,
  Receipt,
  BarChart3,
  Settings,
  Bell,
  Search,
  Menu,
  X,
  ChevronRight,
  LogOut,
  MessageSquare,
  Target,
  Cake,
  Boxes,
  ShieldCheck,
  Palette,
} from 'lucide-react';
import { Button, Modal, Input } from './ui';
import { useAuth, ROLE_LABELS } from '../lib/auth';
import { useTheme } from '../lib/theme';
import { odooApi } from '../services/odoo';

interface LayoutProps {
  children: ReactNode;
  title: string;
  subtitle?: string;
}

const LOGO_SKEEN = '/skeen-brand/logos/Logo%20Completo%20Blanco.png';

const menuGroups = [
  {
    label: 'Principal',
    items: [
      { label: 'Dashboard', icon: LayoutDashboard, href: '/' },
      { label: 'Agenda', icon: Calendar, href: '/agenda' },
    ],
  },
  {
    label: 'Clínica',
    items: [
      { label: 'Pacientes', icon: Users, href: '/pacientes' },
      { label: 'Médicos', icon: Stethoscope, href: '/medicos' },
      { label: 'Servicios', icon: Briefcase, href: '/servicios' },
      { label: 'Productos', icon: Package, href: '/productos' },
    ],
  },
  {
    label: 'Operaciones',
    items: [
      { label: 'Ventas', icon: ShoppingCart, href: '/ventas' },
      { label: 'Pagos', icon: CreditCard, href: '/pagos' },
      { label: 'Monedero', icon: Wallet, href: '/monedero' },
      { label: 'Inventario', icon: Boxes, href: '/inventario' },
      { label: 'Cortes de Caja', icon: Receipt, href: '/cortes' },
    ],
  },
  {
    label: 'Analítica',
    items: [
      { label: 'Reportes', icon: BarChart3, href: '/reportes' },
      { label: 'Configuración', icon: Settings, href: '/configuracion' },
    ],
  },
  {
    label: 'Comunicación',
    items: [
      { label: 'Cumpleañeros', icon: Cake, href: '/cumpleanos' },
    ],
  },
  {
    label: 'Administración',
    items: [
      { label: 'Usuarios', icon: ShieldCheck, href: '/usuarios' },
    ],
  },
  {
    label: 'WACRM',
    items: [
      { label: 'Mensajes', icon: MessageSquare, href: '/wacrm/messages' },
      { label: 'Leads', icon: Target, href: '/wacrm/leads' },
    ],
  },
];

export const SkeenLayout: FC<LayoutProps> = ({ children, title, subtitle }) => {
  const location = useLocation();
  const navigate = useNavigate();
  const { user, canSee, hasRole, logout } = useAuth();
  const { toggleTheme } = useTheme();
  const [sidebarOpen, setSidebarOpen] = useState(false);

  const visibleGroups = useMemo(
    () =>
      menuGroups
        .map((g) => ({ ...g, items: g.items.filter((it) => canSee(it.href)) }))
        .filter((g) => g.items.length > 0),
    [canSee, user]
  );

  const initials = (user?.name || 'US')
    .split(' ')
    .filter(Boolean)
    .slice(0, 2)
    .map((w) => w[0]?.toUpperCase())
    .join('');

  const handleLogout = async () => {
    await logout();
    navigate('/login', { replace: true });
  };

  const [goal, setGoal] = useState<{ goal: number; current: number; pct: number } | null>(null);
  const [goalModalOpen, setGoalModalOpen] = useState(false);
  const [goalInput, setGoalInput] = useState('');
  const [goalSaving, setGoalSaving] = useState(false);

  useEffect(() => {
    let alive = true;
    const fetchGoal = () => {
      odooApi.getSalesGoal()
        .then((res) => {
          if (alive && res.status === 'success') {
            setGoal({ goal: res.goal, current: res.current, pct: res.pct });
          }
        })
        .catch(() => {});
    };
    fetchGoal();
    const id = setInterval(fetchGoal, 60000);
    return () => { alive = false; clearInterval(id); };
  }, []);

  const openGoalModal = () => {
    setGoalInput(goal?.goal ? String(goal.goal) : '');
    setGoalModalOpen(true);
  };

  const saveGoal = async () => {
    const v = parseFloat(goalInput);
    if (Number.isNaN(v) || v < 0) return;
    try {
      setGoalSaving(true);
      await odooApi.setSalesGoal(v);
      setGoal((g) => (g ? { ...g, goal: v, pct: g.current && v ? (g.current / v) * 100 : 0 } : g));
      setGoalModalOpen(false);
    } catch {
      // ignore
    } finally {
      setGoalSaving(false);
    }
  };

  const fmtMoney = (n: number) =>
    n >= 1000000 ? `$${(n / 1000000).toFixed(1)}M` : n >= 1000 ? `$${(n / 1000).toFixed(0)}k` : `$${n.toFixed(0)}`;
  const pctClamped = Math.min(goal?.pct ?? 0, 100);

  useEffect(() => {
    if (!sidebarOpen) return;
    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = originalOverflow;
    };
  }, [sidebarOpen]);

  const isActive = (href: string) => {
    if (href === '/') return location.pathname === '/';
    return location.pathname === href || location.pathname.startsWith(`${href}/`);
  };

  const SidebarContent = () => (
    <>
      <div className="h-20 flex items-center px-5 lg:px-6 border-b border-white/10 shrink-0">
        <img src={LOGO_SKEEN} alt="SKEEN" className="h-7 w-auto object-contain" />
      </div>

      <nav className="flex-1 overflow-y-auto py-5 px-3">
        {visibleGroups.map((group) => (
          <div key={group.label} className="mb-6">
            <p className="px-3 text-[10px] uppercase tracking-wider text-white/40 mb-2 font-heading">{group.label}</p>
            <ul className="space-y-1">
              {group.items.map((item) => {
                const Icon = item.icon;
                const active = isActive(item.href);
                return (
                  <li key={item.label}>
                    <Link
                      to={item.href}
                      onClick={() => setSidebarOpen(false)}
                      className={`flex items-center space-x-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all ${
                        active
                          ? 'bg-theme-accent text-theme-inverse shadow-soft'
                          : 'text-white/70 hover:bg-theme-surface/10 hover:text-white'
                      }`}
                    >
                      <Icon size={18} />
                      <span>{item.label}</span>
                      {active && <ChevronRight size={14} className="ml-auto" />}
                    </Link>
                  </li>
                );
              })}
            </ul>
          </div>
        ))}
      </nav>

      <div className="p-4 border-t border-white/10 shrink-0">
        <div className="flex items-center space-x-3">
          <div className="w-10 h-10 rounded-full bg-theme-accent/20 flex items-center justify-center text-sm font-bold text-theme-accent">
            {initials || 'US'}
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-white truncate">{user?.name || 'Usuario'}</p>
            <p className="text-xs text-white/50 truncate">{user ? ROLE_LABELS[user.role] : ''}</p>
          </div>
          <button
            onClick={handleLogout}
            className="p-2 rounded-lg text-white/50 hover:text-white hover:bg-theme-surface/10"
            title="Cerrar sesión"
            aria-label="Cerrar sesión"
          >
            <LogOut size={18} />
          </button>
        </div>
      </div>
    </>
  );

  return (
    <div className="min-h-screen flex" style={{ backgroundColor: 'var(--bg)', color: 'var(--text)' }}>
      <aside className="hidden lg:flex flex-col w-64 fixed h-full z-20" style={{ backgroundColor: 'var(--sidebar-bg)' }}>
        <SidebarContent />
      </aside>

      {sidebarOpen && (
        <div className="fixed inset-0 bg-black/40 z-30 lg:hidden" onClick={() => setSidebarOpen(false)} aria-hidden="true" />
      )}

      <aside
        className={`fixed inset-y-0 left-0 w-64 z-40 transform transition-transform duration-200 ease-in-out lg:hidden flex flex-col ${
          sidebarOpen ? 'translate-x-0' : '-translate-x-full'
        }`}
        style={{ backgroundColor: 'var(--sidebar-bg)' }}
      >
        <div className="h-20 flex items-center justify-between px-5 border-b border-white/10 shrink-0">
          <img src={LOGO_SKEEN} alt="SKEEN" className="h-7 w-auto object-contain" />
          <Button variant="ghost" size="sm" onClick={() => setSidebarOpen(false)} aria-label="Cerrar menú">
            <X size={22} />
          </Button>
        </div>
        <SidebarContent />
      </aside>

      <div className="flex-1 lg:ml-64 min-h-screen flex flex-col w-full">
        <header className="backdrop-blur border-b sticky top-0 z-10" style={{ backgroundColor: 'var(--header-bg)', borderColor: 'var(--border)' }}>
          <div className="px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-16">
              <div className="flex items-center space-x-3 min-w-0">
                <Button
                  variant="ghost"
                  size="sm"
                  className="lg:hidden"
                  style={{ color: 'var(--text-heading)' }}
                  onClick={() => setSidebarOpen(true)}
                  aria-label="Abrir menú"
                >
                  <Menu size={22} />
                </Button>
                <div className="min-w-0">
                  <h2 className="text-lg font-bold truncate font-heading tracking-tight" style={{ color: 'var(--text-heading)' }}>{title}</h2>
                  {subtitle && <p className="text-xs hidden sm:block truncate" style={{ color: 'var(--text-muted)' }}>{subtitle}</p>}
                </div>
              </div>

              <div className="flex items-center space-x-2 sm:space-x-3 shrink-0">
                {goal && goal.goal > 0 && (
                  <button
                    onClick={hasRole('admin') ? openGoalModal : undefined}
                    className={`hidden md:flex flex-col w-44 xl:w-56 text-left rounded-xl border px-3 py-1.5 shadow-card ${hasRole('admin') ? 'cursor-pointer' : 'cursor-default'}`}
                    style={{ borderColor: 'var(--border)', backgroundColor: 'var(--surface)' }}
                    title={hasRole('admin') ? 'Click para editar la meta' : 'Meta de ventas del mes'}
                  >
                    <div className="flex items-center justify-between text-[11px] mb-1" style={{ color: 'var(--text-muted)' }}>
                      <span className="flex items-center gap-1"><Target size={12} /> Meta del mes</span>
                      <span className="font-bold" style={{ color: 'var(--text-heading)' }}>{Math.round(goal.pct)}%</span>
                    </div>
                    <div className="w-full h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: 'var(--bg)' }}>
                      <div className="h-full rounded-full transition-all" style={{ width: `${pctClamped}%`, backgroundColor: goal.pct >= 100 ? 'var(--success)' : 'var(--accent)' }} />
                    </div>
                    <div className="flex items-center justify-between text-[11px] mt-1">
                      <span className="font-semibold" style={{ color: 'var(--text-heading)' }}>{fmtMoney(goal.current)}</span>
                      <span style={{ color: 'var(--text-muted)' }}>de {fmtMoney(goal.goal)}</span>
                    </div>
                  </button>
                )}
                {goal && goal.goal <= 0 && hasRole('admin') && (
                  <Button variant="outline" size="sm" className="hidden md:inline-flex" onClick={openGoalModal}>
                    <Target size={14} className="mr-1.5" /> Definir meta
                  </Button>
                )}
                <div className="hidden md:flex items-center rounded-full px-3 py-1.5 border" style={{ backgroundColor: 'var(--bg)', borderColor: 'var(--border)' }}>
                  <Search size={14} style={{ color: 'var(--text-muted)' }} />
                  <input
                    type="text"
                    placeholder="Buscar paciente, cita..."
                    className="bg-transparent border-none text-sm ml-2 focus:outline-none w-48 placeholder:text-theme-muted/60"
                    style={{ color: 'var(--text-heading)' }}
                  />
                </div>
                <button className="p-2 rounded-full relative transition" style={{ color: 'var(--text-muted)' }}
                  onMouseEnter={(e) => e.currentTarget.style.backgroundColor = 'var(--accent-bg)'}
                  onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}
                >
                  <Bell size={18} />
                  <span className="absolute top-1 right-1 w-2 h-2 rounded-full" style={{ backgroundColor: 'var(--accent)' }} />
                </button>
                <button
                  onClick={toggleTheme}
                  title="Cambiar a HomeNest"
                  className="hidden sm:inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-full text-xs font-medium transition border"
                  style={{ backgroundColor: 'var(--surface)', color: 'var(--text-heading)', borderColor: 'var(--border)' }}
                  onMouseEnter={(e) => e.currentTarget.style.backgroundColor = 'var(--accent-bg)'}
                  onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'var(--surface)'}
                >
                  <Palette size={14} />
                  HomeNest
                </button>
              </div>
            </div>
          </div>
        </header>

        <main className="flex-1 w-full px-4 sm:px-6 lg:px-8 py-6 sm:py-8">
          {children}
        </main>
      </div>

      <Modal
        isOpen={goalModalOpen}
        onClose={() => setGoalModalOpen(false)}
        title="Meta de ventas del mes"
        maxWidth="sm"
        footer={
          <>
            <Button variant="outline" onClick={() => setGoalModalOpen(false)}>Cancelar</Button>
            <Button onClick={saveGoal} loading={goalSaving}>Guardar meta</Button>
          </>
        }
      >
        <div className="space-y-3">
          <p className="text-sm" style={{ color: 'var(--text-muted)' }}>Define el objetivo de ventas (MXN) para el mes en curso. La barra del header muestra el avance en tiempo real.</p>
          <Input label="Meta mensual (MXN)" type="number" min={0} step={1000} value={goalInput} onChange={(e) => setGoalInput(e.target.value)} placeholder="ej. 500000" />
        </div>
      </Modal>
    </div>
  );
};

export default SkeenLayout;
