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,
  Wallet,
  CreditCard,
  ShoppingCart,
  Receipt,
  Store,
  BarChart3,
  Settings,
  Menu,
  X,
  ChevronRight,
  LogOut,
  MessageSquare,
  Target,
  Cake,
  Boxes,
  ClipboardList,
  ClipboardPlus,
  Banknote,
  Percent,
  FolderClock,
  Star,
  Pencil,
  ChevronUp,
  ChevronDown,
} from 'lucide-react';
import { Button, Modal, Input } from './ui';
import QuickLinksDock, { QuickLinksModePicker } from './QuickLinksDock';
import GlobalSearch from './GlobalSearch';
import ThemePicker from './ThemePicker';
import NotificationBell from './NotificationBell';
import { useAuth, ROLE_LABELS } from '../lib/auth';
import { useQuickLinks } from '../lib/quicklinks';
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: 'Visitas', icon: ClipboardList, href: '/visitas' },
      { label: 'Consultas', icon: ClipboardPlus, href: '/consultas' },
      { label: 'Expedientes', icon: FolderClock, href: '/expedientes' },
      { label: 'Médicos', icon: Stethoscope, href: '/medicos' },
      { label: 'Servicios', icon: Briefcase, href: '/servicios' },
    ],
  },
  {
    label: 'Operaciones',
    items: [
      { label: 'Punto de Venta', icon: Store, href: '/pos' },
      { label: 'Ventas', icon: ShoppingCart, href: '/ventas' },
      { label: 'Pagos', icon: CreditCard, href: '/pagos' },
      { label: 'Adeudos', icon: Banknote, href: '/reportes?tab=adeudos' },
      { 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: 'Comisiones', icon: Percent, href: '/reportes?tab=comisiones' },
      { label: 'Configuración', icon: Settings, href: '/configuracion' },
    ],
  },
  {
    label: 'Comunicación',
    items: [
      { label: 'Cumpleañeros', icon: Cake, href: '/cumpleanos' },
    ],
  },
  {
    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 [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]
  );

  // Accesos rápidos personalizables (localStorage por usuario)
  const quick = useQuickLinks();
  const dockItems = useMemo(
    () => menuGroups.flatMap((g) => g.items).filter((it) => canSee(it.href)),
    [canSee]
  );
  const quickItems = useMemo(
    () =>
      quick.links
        .filter((href) => canSee(href))
        .map((href) => {
          for (const g of menuGroups) {
            const found = g.items.find((it) => it.href === href);
            if (found) return found;
          }
          return null;
        })
        .filter((it): it is (typeof menuGroups)[number]['items'][number] => it !== null),
    [quick.links, canSee]
  );

  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">
        {quickItems.length > 0 && quick.mode === 'menu' && (
          <div className="mb-6">
            <div className="flex items-center justify-between px-3 mb-2">
              <p className="text-[10px] uppercase tracking-wider text-white/40 font-heading">Accesos rápidos</p>
              <span className="flex items-center gap-1">
                <QuickLinksModePicker direction="down" align="right" />
                <button
                  type="button"
                  onClick={() => quick.setEditing(!quick.editing)}
                  className="text-white/40 hover:text-white transition-colors"
                  title={quick.editing ? 'Terminar edición' : 'Editar accesos rápidos'}
                >
                  {quick.editing ? <X size={13} /> : <Pencil size={12} />}
                </button>
              </span>
            </div>
            <ul className="space-y-1">
              {quickItems.map((item, idx) => {
                const Icon = item.icon;
                const active = isActive(item.href);
                return (
                  <li key={item.href} className="flex items-center gap-1">
                    <Link
                      to={item.href}
                      onClick={() => setSidebarOpen(false)}
                      className={`flex-1 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>
                    </Link>
                    {quick.editing && (
                      <span className="flex items-center gap-0.5 shrink-0">
                        <button type="button" onClick={() => quick.move(item.href, -1)} disabled={idx === 0}
                          className="text-white/40 hover:text-white disabled:opacity-30 transition-colors" title="Subir">
                          <ChevronUp size={14} />
                        </button>
                        <button type="button" onClick={() => quick.move(item.href, 1)} disabled={idx === quickItems.length - 1}
                          className="text-white/40 hover:text-white disabled:opacity-30 transition-colors" title="Bajar">
                          <ChevronDown size={14} />
                        </button>
                        <button type="button" onClick={() => quick.remove(item.href)}
                          className="text-white/40 hover:text-rose-400 transition-colors" title="Quitar">
                          <X size={14} />
                        </button>
                      </span>
                    )}
                  </li>
                );
              })}
            </ul>
          </div>
        )}
        {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);
                const pinned = quick.isPinned(item.href);
                return (
                  <li key={item.label} className="group flex items-center gap-1">
                    <Link
                      to={item.href}
                      onClick={() => setSidebarOpen(false)}
                      className={`flex-1 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>
                    <button
                      type="button"
                      onClick={() => quick.toggle(item.href)}
                      className={`shrink-0 transition-all ${
                        pinned ? 'text-amber-400' : 'text-white/30 opacity-0 group-hover:opacity-100 hover:text-amber-400'
                      }`}
                      title={pinned ? 'Quitar de accesos rápidos' : 'Fijar en accesos rápidos'}
                    >
                      <Star size={15} fill={pinned ? 'currentColor' : 'none'} />
                    </button>
                  </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>
                )}
                <GlobalSearch className="hidden md:block" />
                <NotificationBell buttonClassName="p-2 rounded-full relative transition text-theme-muted hover:bg-theme-accent-bg hover:text-theme-heading" />
                <ThemePicker />
              </div>
            </div>
          </div>
        </header>

        <main className={`flex-1 w-full px-4 sm:px-6 lg:px-8 py-6 sm:py-8 ${quick.mode === 'right' ? 'lg:pr-20' : ''} ${quick.mode === 'bottom' ? 'pb-20' : ''}`}>
          {children}
        </main>
      </div>

      <QuickLinksDock items={dockItems} />

      <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;
