import { Navigate, Outlet, useLocation, Link } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import {
  LogOut, LayoutDashboard, FolderTree, Users,
  FileText, DollarSign, Eye, History, User as ClientIcon, Search, Tag
} from 'lucide-react';
import { useState, useEffect } from 'react';
import api from '../services/api';

export default function ProtectedLayout() {
  const { isAuthenticated, role, logout } = useAuthStore();
  const location = useLocation();

  if (!isAuthenticated) return <Navigate to="/login" replace />;

  const [unreadCount, setUnreadCount] = useState(0);

  useEffect(() => {
    if (isAuthenticated && (role === 'Admin' || role === 'Moderador')) {
      const loadCount = async () => {
        try {
          const res = await api.get('/moderationstats/unread-count');
          setUnreadCount(res.data);
        } catch { /* silence */ }
      };

      const handleUpdate = (e: any) => {
        if (e.detail !== undefined) setUnreadCount(e.detail);
        else loadCount();
      };

      loadCount();
      window.addEventListener('moderation-unread-changed', handleUpdate);
      const interval = setInterval(loadCount, 60000);
      return () => {
        window.removeEventListener('moderation-unread-changed', handleUpdate);
        clearInterval(interval);
      };
    }
  }, [isAuthenticated, role]);

  // Definición de permisos por ruta
  const menuItems = [
    { label: 'Dashboard', href: '/', icon: <LayoutDashboard size={20} />, roles: ['Admin', 'Cajero'] },
    { label: 'Moderación', href: '/moderation', icon: <Eye size={20} />, roles: ['Admin', 'Moderador'], badge: unreadCount },
    { label: 'Explorador', href: '/listings', icon: <Search size={20} />, roles: ['Admin', 'Cajero', 'Moderador'] },
    { label: 'Clientes', href: '/clients', icon: <ClientIcon size={20} />, roles: ['Admin', 'Cajero'] },
    { label: 'Categorías', href: '/categories', icon: <FolderTree size={20} />, roles: ['Admin'] },
    { label: 'Usuarios', href: '/users', icon: <Users size={20} />, roles: ['Admin'] },
    { label: 'Tarifas', href: '/pricing', icon: <DollarSign size={20} />, roles: ['Admin'] },
    { label: 'Promociones', href: '/promotions', icon: <Tag size={20} />, roles: ['Admin'] },
    { label: 'Cupones', href: '/coupons', icon: <Tag size={20} />, roles: ['Admin'] },
    { label: 'Diagramación', href: '/diagram', icon: <FileText size={20} />, roles: ['Admin', 'Diagramador'] },
    { label: 'Auditoría', href: '/audit', icon: <History size={20} />, roles: ['Admin'] },
  ];

  return (
    <div className="flex h-screen bg-gray-100 overflow-hidden">
      <aside className="w-64 bg-gray-900 text-white flex flex-col shadow-xl">
        <div className="p-6 text-xl font-black border-b border-gray-800 tracking-tighter italic text-blue-500">
          SIG-CM <span className="text-[10px] text-gray-500 not-italic font-medium">ADMIN</span>
        </div>

        <nav className="flex-1 p-4 space-y-1">
          {menuItems.map((item) => {
            // FILTRO DE SEGURIDAD UI: Solo mostrar si el rol del usuario está permitido
            if (!item.roles.includes(role || '')) return null;

            return (
              <Link
                key={item.href}
                to={item.href}
                className={`flex items-center justify-between p-3 rounded-xl transition-all ${location.pathname === item.href
                  ? 'bg-blue-600 text-white shadow-lg shadow-blue-900/20'
                  : 'text-gray-400 hover:bg-gray-800 hover:text-white'
                  }`}
              >
                <div className="flex items-center gap-3">
                  {item.icon}
                  <span className="font-medium text-sm">{item.label}</span>
                </div>
                {(item as any).badge > 0 && (
                  <span className={`px-2 py-0.5 rounded-full text-[10px] font-black ${location.pathname === item.href ? 'bg-white text-blue-600' : 'bg-rose-500 text-white'}`}>
                    {(item as any).badge}
                  </span>
                )}
              </Link>
            );
          })}
        </nav>

        <div className="p-4 border-t border-gray-800">
          <div className="mb-4 px-3 py-2 bg-gray-800/50 rounded-lg">
            <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest">Sesión actual</p>
            <p className="text-xs font-bold text-blue-400">{role}</p>
          </div>
          <button onClick={logout} className="flex items-center gap-3 text-red-400 hover:text-red-300 w-full p-2 transition-colors text-sm font-bold">
            <LogOut size={18} /> Cerrar Sesión
          </button>
        </div>
      </aside>

      <main className="flex-1 overflow-y-auto p-8 relative">
        <Outlet />
      </main>
    </div>
  );
}