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,
} from 'lucide-react';
import { Button, Modal, Input } from './ui';
import { useAuth, ROLE_LABELS } from '../lib/auth';
import { odooApi } from '../services/odoo';

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

const LOGO_BROWN = '/skeen-brand/logos/Logo%20Completo%20Negro.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' },
    ],
  },
];

const Layout: 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]
  );

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

  // Meta de ventas mensual (header widget)
  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-homenest-sand shrink-0">
        <img
          src={LOGO_BROWN}
          alt="SKEEN"
          className="h-8 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-homenest-bark-muted/60 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-homenest-brown text-homenest-cream-light shadow-soft'
                          : 'text-homenest-bark-muted hover:bg-homenest-sand-light hover:text-homenest-bark'
                      }`}
                    >
                      <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-homenest-sand shrink-0">
        <div className="flex items-center space-x-3">
          <div className="w-10 h-10 rounded-full bg-homenest-sage-light flex items-center justify-center text-sm font-bold text-homenest-sage-dark">
            {initials || 'US'}
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-homenest-bark truncate">{user?.name || 'Usuario'}</p>
            <p className="text-xs text-homenest-bark-muted truncate">{user ? ROLE_LABELS[user.role] : ''}</p>
          </div>
          <button
            onClick={handleLogout}
            className="p-2 rounded-lg text-homenest-bark-muted hover:text-homenest-bark hover:bg-homenest-sand-light"
            title="Cerrar sesión"
            aria-label="Cerrar sesión"
          >
            <LogOut size={18} />
          </button>
        </div>
      </div>
    </>
  );

  return (
    <div className="min-h-screen bg-homenest-cream text-homenest-bark flex">
      {/* Sidebar desktop */}
      <aside className="hidden lg:flex flex-col w-64 bg-homenest-cream-light fixed h-full z-20 border-r border-homenest-sand shadow-soft">
        <SidebarContent />
      </aside>

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

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

      {/* Main content */}
      <div className="flex-1 lg:ml-64 min-h-screen flex flex-col w-full">
        <header className="bg-homenest-cream-light/80 backdrop-blur border-b border-homenest-sand sticky top-0 z-10">
          <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 text-homenest-bark"
                  onClick={() => setSidebarOpen(true)}
                  aria-label="Abrir menú"
                >
                  <Menu size={22} />
                </Button>
                <div className="min-w-0">
                  <h2 className="text-lg font-bold text-homenest-bark truncate font-heading tracking-tight">{title}</h2>
                  {subtitle && <p className="text-xs text-homenest-bark-muted hidden sm:block truncate">{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 border-homenest-sand bg-homenest-cream-light px-3 py-1.5 shadow-card ${hasRole('admin') ? 'hover:border-homenest-brown cursor-pointer' : 'cursor-default'}`}
                    title={hasRole('admin') ? 'Click para editar la meta' : 'Meta de ventas del mes'}
                  >
                    <div className="flex items-center justify-between text-[11px] text-homenest-bark-muted mb-1">
                      <span className="flex items-center gap-1"><Target size={12} /> Meta del mes</span>
                      <span className="font-bold text-homenest-bark">{Math.round(goal.pct)}%</span>
                    </div>
                    <div className="w-full h-1.5 bg-homenest-cream rounded-full overflow-hidden">
                      <div
                        className={`h-full rounded-full transition-all ${goal.pct >= 100 ? 'bg-homenest-sage' : 'bg-homenest-brown'}`}
                        style={{ width: `${pctClamped}%` }}
                      />
                    </div>
                    <div className="flex items-center justify-between text-[11px] mt-1">
                      <span className="font-semibold text-homenest-bark">{fmtMoney(goal.current)}</span>
                      <span className="text-homenest-bark-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 bg-homenest-cream rounded-full px-3 py-1.5 border border-homenest-sand focus-within:border-homenest-brown">
                  <Search size={14} className="text-homenest-bark-muted" />
                  <input
                    type="text"
                    placeholder="Buscar paciente, cita..."
                    className="bg-transparent border-none text-sm ml-2 focus:outline-none w-48 text-homenest-bark placeholder:text-homenest-bark-muted/60"
                  />
                </div>
                <button className="p-2 rounded-full text-homenest-bark-muted hover:bg-homenest-cream-dark relative">
                  <Bell size={18} />
                  <span className="absolute top-1 right-1 w-2 h-2 bg-homenest-brown rounded-full" />
                </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 text-homenest-bark-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 Layout;
