import { useState } from 'react';
import {
  LayoutDashboard,
  Bed,
  Users,
  ClipboardList,
  FileText,
  Activity,
  Microscope,
  Menu,
  Sun,
  Moon,
  LogOut,
  UserCog,
  Terminal
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Sheet, SheetContent, SheetTrigger, SheetTitle, SheetDescription, SheetHeader } from '@/components/ui/sheet';

import type { Vista, Usuario } from '@/types';

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useTheme } from "@/components/theme-provider"

interface LayoutProps {
  children: React.ReactNode;
  vistaActual: Vista;
  onCambiarVista: (vista: Vista) => void;
  currentUser: Usuario | null;
  onLogout: () => void;
}

export function Layout({ children, vistaActual, onCambiarVista, currentUser, onLogout }: LayoutProps) {
  const { theme, setTheme } = useTheme()
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  const toggleDarkMode = () => setTheme(theme === "dark" ? "light" : "dark")

  const menuItems: { vista: Vista; label: string; icon: React.ElementType; rolRequerido?: string }[] = [
    { vista: 'dashboard', label: 'Dashboard', icon: LayoutDashboard },
    { vista: 'camas', label: 'Camas', icon: Bed, rolRequerido: 'medico' },
    { vista: 'pacientes', label: 'Pacientes', icon: Users },
    { vista: 'internaciones', label: 'Internaciones', icon: ClipboardList },
    { vista: 'evoluciones', label: 'Evoluciones', icon: FileText },
    { vista: 'cultivos', label: 'Cultivos', icon: Microscope },
  ];

  const filteredMenuItems = menuItems.filter(item => {
    const rol = currentUser?.rol as string | undefined;
    if (!item.rolRequerido) return true;
    if (rol === 'admin') return true;
    if (item.rolRequerido === 'medico' && (rol === 'medico' || rol === 'admin')) return true;
    return false;
  });

  if ((currentUser?.rol as string) === 'admin') {
    filteredMenuItems.push({ vista: 'usuarios', label: 'Usuarios', icon: UserCog });
    filteredMenuItems.push({ vista: 'sistema', label: 'Sistema', icon: Terminal });
  }

  const renderNavContent = (onItemClick?: () => void) => (
    <nav className="flex flex-col gap-2">
      {filteredMenuItems.map((item) => {
        const Icon = item.icon;
        const isActive = vistaActual === item.vista;
        return (
          <Button
            key={item.vista}
            variant={isActive ? 'default' : 'ghost'}
            className={`justify-start gap-3 ${isActive ? 'bg-blue-600 hover:bg-blue-700 text-white' : 'hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-gray-200'}`}
            onClick={() => {
              onCambiarVista(item.vista);
              if (onItemClick) onItemClick();
            }}
          >
            <Icon className="h-5 w-5" />
            <span>{item.label}</span>
          </Button>
        );
      })}
    </nav>
  );

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex">
      {/* Sidebar Desktop */}
      <aside className="hidden lg:flex w-64 flex-col bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 fixed h-full">
        <div className="p-6 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 bg-blue-600 rounded-lg flex items-center justify-center">
              <Activity className="h-6 w-6 text-white" />
            </div>
            <div>
              <h1 className="font-bold text-lg text-gray-900 dark:text-white leading-tight">Historia Clinica Electrónica</h1>
              <p className="text-xs text-gray-500 dark:text-gray-400">Servicio Clínica Médica - Hospital Santojanni</p>
            </div>
          </div>
        </div>
        <div className="flex-1 p-4 overflow-auto">
          {renderNavContent()}
        </div>
        <div className="p-4 border-t border-gray-200 dark:border-gray-700">
          <div className="text-sm text-gray-600 dark:text-gray-300 mb-2">
            <div className="font-medium">{currentUser?.apellido}, {currentUser?.nombre}</div>
            <div className="text-xs text-gray-500 dark:text-gray-400 capitalize">{currentUser?.rol}</div>
          </div>
          <div className="flex items-center justify-center gap-2">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="icon">
                  <Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
                  <Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
                  <span className="sr-only">Toggle theme</span>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => setTheme("light")}>
                  Light
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setTheme("dark")}>
                  Dark
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setTheme("system")}>
                  System
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
            <Button variant="outline" size="icon" onClick={onLogout} title="Cerrar sesión">
              <LogOut className="h-4 w-4" />
            </Button>
          </div>
          <div className="text-xs text-gray-400 dark:text-gray-500 text-center mt-2">
            v2.0
          </div>
        </div>
      </aside>

      {/* Header Mobile */}
      <header className="lg:hidden fixed top-0 left-0 right-0 h-16 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 z-50 flex items-center justify-between px-4">
        <div className="flex items-center gap-3">
          <div className="h-8 w-8 bg-blue-600 rounded-lg flex items-center justify-center">
            <Activity className="h-5 w-5 text-white" />
          </div>
          <span className="font-bold text-gray-900 dark:text-white">Gestion Historia Clinica Electronica</span>
        </div>
        <Sheet open={mobileMenuOpen} onOpenChange={setMobileMenuOpen}>
          <SheetTrigger asChild>
            <Button variant="ghost" size="icon" className="dark:text-white" onClick={() => setMobileMenuOpen(true)}>
              <Menu className="h-6 w-6" />
            </Button>
          </SheetTrigger>
          <SheetContent side="right" className="w-64 p-0 dark:bg-gray-800">
            <SheetHeader className="sr-only">
              <SheetTitle>Menú de navegación</SheetTitle>
              <SheetDescription>Navegación principal de la aplicación</SheetDescription>
            </SheetHeader>
            <div className="p-6 border-b border-gray-200 dark:border-gray-700">
              <div className="flex items-center justify-between">
                <span className="font-bold text-lg dark:text-white">Menú</span>
              </div>
              <div className="mt-2 text-sm text-gray-600 dark:text-gray-300">
                <div className="font-medium">{currentUser?.apellido}, {currentUser?.nombre}</div>
                <div className="text-xs text-gray-500 dark:text-gray-400 capitalize">{currentUser?.rol}</div>
              </div>
            </div>
            <div className="p-4">
              {renderNavContent(() => setMobileMenuOpen(false))}
            </div>
            <div className="p-4 border-t border-gray-200 dark:border-gray-700 space-y-2">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  toggleDarkMode();
                  setMobileMenuOpen(false);
                }}
                className="w-full flex items-center justify-center gap-2 dark:text-white"
              >
                {theme === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
                <span className="text-sm">{theme === "dark" ? 'Modo Claro' : 'Modo Oscuro'}</span>
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  onLogout();
                  setMobileMenuOpen(false);
                }}
                className="w-full flex items-center justify-center gap-2 dark:text-white"
              >
                <LogOut className="h-4 w-4" />
                <span className="text-sm">Cerrar Sesión</span>
              </Button>
            </div>
          </SheetContent>
        </Sheet>
      </header>

      {/* Main Content */}
      <main className="flex-1 min-w-0 lg:ml-64 pt-16 lg:pt-0 min-h-screen">
        <div className="p-4 lg:p-8 max-w-7xl mx-auto w-full">
          {children}
        </div>
      </main>
    </div>
  );
}