import { useEffect, useState } from 'react';
import { Outlet, useNavigate, useLocation, Link } from 'react-router-dom';
import {
  LayoutDashboard, PlusCircle, Banknote, LogOut,
  ChevronLeft, ChevronRight, Settings, Bell,
  User as UserIcon, Monitor,
  TrendingUp, ClipboardList, ShieldCheck
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import clsx from 'clsx';
import NotificationDropdown from '../components/NotificationDropdown';
import SettingsPanel from '../components/SettingsPanel';
import api from '../services/api';

export default function CounterLayout() {
  const navigate = useNavigate();
  const location = useLocation();
  const [isSidebarOpen, setIsSidebarOpen] = useState(true);
  const [notifications, setNotifications] = useState<any>({ items: [], unreadCount: 0 });
  const [showNotifications, setShowNotifications] = useState(false);
  const [showSettings, setShowSettings] = useState(false);

  // Parsing del usuario más seguro
  const storedUser = localStorage.getItem('user');
  const user = storedUser && storedUser.startsWith('{')
    ? JSON.parse(storedUser)
    : { username: storedUser || "Admin" };

  const handleLogout = () => {
    if (confirm('¿Cerrar sesión de caja?')) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      navigate('/login');
    }
  };

  const fetchNotifications = async () => {
    try {
      const res = await api.get('/notifications');
      setNotifications(res.data);
    } catch (e) { console.error("Error al obtener notificaciones", e); }
  };

  // Listener de atajos de teclado completo (F1 - F9)
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      const map: Record<string, string> = {
        'F1': '/dashboard',
        'F2': '/nuevo-aviso',
        'F4': '/caja',
        'F6': '/analitica',
        'F8': '/historial',
        'F9': '/tesoreria'
      };

      if (map[e.key]) {
        e.preventDefault();
        navigate(map[e.key]);
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [navigate]);

  useEffect(() => {
    fetchNotifications();
    const interval = setInterval(fetchNotifications, 60000);
    return () => clearInterval(interval);
  }, []);

  const menuItems = [
    { path: '/dashboard', label: 'Panel Principal', icon: LayoutDashboard, shortcut: 'F1' },
    { path: '/nuevo-aviso', label: 'Nuevo Aviso', icon: PlusCircle, shortcut: 'F2' },
    { path: '/caja', label: 'Caja Diaria', icon: Banknote, shortcut: 'F4' },
    { path: '/historial', label: 'Consultas', icon: ClipboardList, shortcut: 'F8' },
    { path: '/analitica', label: 'Analítica', icon: TrendingUp, shortcut: 'F6' },
    { path: '/tesoreria', label: 'Tesorería', icon: ShieldCheck, shortcut: 'F9' },
  ];

  return (
    <div className="flex h-screen bg-[#f8fafc] overflow-hidden">
      {/* --- SIDEBAR --- */}
      <motion.aside
        initial={false}
        animate={{ width: isSidebarOpen ? 260 : 80 }}
        className="relative bg-slate-900 text-slate-300 flex flex-col z-30 shadow-2xl"
      >
        <div className="p-6 flex items-center gap-3 border-b border-slate-800/50">
          <div className="bg-blue-600 p-2 rounded-xl shadow-lg shadow-blue-500/20">
            <Monitor size={20} className="text-white" />
          </div>
          {isSidebarOpen && (
            <motion.span initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="font-bold text-xl tracking-tight text-white">
              SIG-CM
            </motion.span>
          )}
        </div>

        <nav className="flex-1 px-4 py-6 space-y-2 overflow-y-auto custom-scrollbar">
          {menuItems.map((item) => {
            const isActive = location.pathname === item.path;
            return (
              <Link
                key={item.path}
                to={item.path}
                className={clsx(
                  "flex items-center gap-3 px-3 py-3 rounded-xl transition-all group relative",
                  isActive ? "bg-blue-600 text-white shadow-lg shadow-blue-500/20" : "hover:bg-slate-800 hover:text-white"
                )}
              >
                <item.icon size={22} className={clsx(isActive ? "text-white" : "text-slate-400 group-hover:text-blue-400")} />
                {isSidebarOpen && (
                  <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex-1 flex justify-between items-center">
                    <span className="font-medium">{item.label}</span>
                    <span className="text-[10px] bg-slate-800 px-1.5 py-0.5 rounded opacity-50 font-mono">{item.shortcut}</span>
                  </motion.div>
                )}
              </Link>
            );
          })}
        </nav>

        <div className="p-4 border-t border-slate-800/50">
          <button onClick={handleLogout} className="flex items-center gap-3 w-full px-3 py-3 rounded-xl hover:bg-rose-500/10 hover:text-rose-400 transition-colors group">
            <LogOut size={22} className="text-slate-500 group-hover:text-rose-400" />
            {isSidebarOpen && <span className="font-medium text-sm">Cerrar Sesión</span>}
          </button>
        </div>

        <button onClick={() => setIsSidebarOpen(!isSidebarOpen)} className="absolute -right-3 top-20 bg-white text-slate-900 border border-slate-200 rounded-full p-1 shadow-md hover:scale-110 transition-transform hidden lg:block">
          {isSidebarOpen ? <ChevronLeft size={14} /> : <ChevronRight size={14} />}
        </button>
      </motion.aside>

      {/* --- MAIN CONTENT --- */}
      <div className="flex-1 flex flex-col min-w-0 overflow-hidden">

        {/* TOP HEADER */}
        <header className="h-16 bg-white/80 backdrop-blur-md border-b border-slate-200 px-8 flex items-center justify-between z-20 sticky top-0">
          <div className="flex items-center gap-4 flex-1">
            {/* Buscador eliminado por redundancia */}
          </div>

          <div className="flex items-center gap-4">

            {/* CAMPANITA */}
            <div className="relative">
              <button
                onClick={() => setShowNotifications(!showNotifications)}
                className={clsx(
                  "relative p-2.5 rounded-xl transition-all",
                  showNotifications ? "bg-blue-600 text-white shadow-lg" : "text-slate-500 hover:text-blue-600 hover:bg-slate-100"
                )}
              >
                <Bell size={20} />
                {notifications.unreadCount > 0 && (
                  <span className="absolute top-1.5 right-1.5 w-4 h-4 bg-rose-500 text-white text-[9px] font-black flex items-center justify-center rounded-full border-2 border-white shadow-sm">
                    {notifications.unreadCount}
                  </span>
                )}
              </button>

              <AnimatePresence>
                {showNotifications && (
                  <NotificationDropdown
                    notifications={notifications.items}
                    onClose={() => setShowNotifications(false)}
                    onRefresh={fetchNotifications}
                  />
                )}
              </AnimatePresence>
            </div>

            {/* ENGRANAJE */}
            <button
              onClick={() => setShowSettings(true)}
              className={clsx(
                "p-2.5 rounded-xl transition-all",
                showSettings ? "bg-blue-600 text-white shadow-lg" : "text-slate-500 hover:text-blue-600 hover:bg-slate-100"
              )}
            >
              <Settings size={20} />
            </button>

            <div className="h-6 w-px bg-slate-200 mx-2" />

            {/* USUARIO */}
            <div className="flex items-center gap-3">
              <div className="text-right hidden sm:block">
                <p className="text-sm font-black text-slate-900 leading-none">{user.username}</p>
                <p className="text-[10px] font-bold text-slate-400 uppercase tracking-tighter mt-1">Cajero Central</p>
              </div>
              <div className="h-10 w-10 rounded-[1rem] bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white shadow-lg border-2 border-white">
                <UserIcon size={20} />
              </div>
            </div>
          </div>
        </header>

        <main className="flex-1 overflow-y-auto bg-[#f8fafc]">
          <Outlet />
        </main>
      </div>

      {/* PANEL DE AJUSTES (Movido fuera del flujo del header para mejor renderizado) */}
      <AnimatePresence>
        {showSettings && (
          <SettingsPanel onClose={() => setShowSettings(false)} />
        )}
      </AnimatePresence>
    </div>
  );
}