'use client';

import Link from 'next/link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import { cn } from '@horux/shared-ui';
import {
  LayoutDashboard,
  FileText,
  Calculator,
  Settings,
  LogOut,
  BarChart3,
  Calendar,
  Bell,
  Users,
  Building2,
  UserCog,
  CreditCard,
  Send,
  Scale,
  FileCheck,
  FileWarning,
  Receipt,
  Shield,
  Rocket,
  ClipboardList,
  ListChecks,
  Gift,
  CheckSquare2,
} from 'lucide-react';
import { useAuthStore } from '@/stores/auth-store';
import { logout } from '@/lib/api/auth';
import { useContribuyentes } from '@/lib/hooks/use-contribuyentes';
import { useNavGate } from '@/lib/hooks/use-nav-gate';
import { useRouter } from 'next/navigation';
import { hasDespachoFeature, isGlobalAdminRfc, type DespachoPlan } from '@horux/shared';

interface NavItem {
  name: string;
  href: string;
  icon: typeof LayoutDashboard;
  feature?: string;  // Required plan feature — hidden if tenant's plan lacks it
  roles?: string[];  // Allowed roles — hidden if user's role is not in the list
  /** Visible solo si el user es owner en algún tenant (no en el activo). */
  requireOwnerSomewhere?: boolean;
}

const navigation: NavItem[] = [
  { name: 'Despacho', href: '/despachos', icon: ListChecks, roles: ['owner', 'cfo', 'contador', 'auxiliar', 'supervisor'] },
  { name: 'Dashboard', href: '/dashboard', icon: LayoutDashboard, roles: ['owner', 'cfo', 'contador', 'auxiliar', 'supervisor', 'cliente'] },
  { name: 'CFDI', href: '/cfdi', icon: FileText },
  { name: 'Impuestos', href: '/impuestos', icon: Calculator },
  { name: 'Reportes', href: '/reportes', icon: BarChart3, feature: 'reportes', roles: ['owner', 'cfo', 'supervisor', 'cliente'] },
  { name: 'Conciliacion', href: '/conciliacion', icon: Scale, feature: 'conciliacion' },
  { name: 'Calendario', href: '/calendario', icon: Calendar, feature: 'calendario' },
  { name: 'Alertas', href: '/alertas', icon: Bell, feature: 'alertas' },
  { name: 'Facturación', href: '/facturacion', icon: Send, roles: ['owner', 'cfo', 'contador', 'auxiliar', 'supervisor'] },
  { name: 'Documentos', href: '/documentos', icon: FileCheck, feature: 'documentos' },
  { name: 'Carteras', href: '/carteras', icon: ClipboardList, roles: ['supervisor', 'auxiliar'] },
  { name: 'Contribuyentes', href: '/contribuyentes', icon: Building2, roles: ['owner', 'cfo', 'supervisor', 'contador', 'auxiliar'] },
  { name: 'Usuarios', href: '/usuarios', icon: Users, roles: ['owner', 'cfo'] },
  { name: 'Tareas', href: '/tareas', icon: CheckSquare2, roles: ['owner', 'cfo', 'contador', 'auxiliar', 'supervisor'] },
  { name: 'Planes', href: '/configuracion/planes-despacho', icon: CreditCard, roles: ['owner', 'cfo'] },
  { name: 'Configuracion', href: '/configuracion', icon: Settings, roles: ['owner', 'cfo'] },
];

const adminNavigation: NavItem[] = [
  { name: 'Clientes', href: '/clientes', icon: Building2 },
  { name: 'Admin Usuarios', href: '/admin/usuarios', icon: UserCog },
  { name: 'Staff', href: '/admin/staff', icon: Shield },
  { name: 'Audit Log', href: '/admin/audit-log', icon: FileWarning },
];

export function Sidebar() {
  const pathname = usePathname();
  const router = useRouter();
  const { user, logout: clearAuth } = useAuthStore();

  const handleLogout = async () => {
    try {
      await logout();
    } catch {
      // Ignore errors
    } finally {
      clearAuth();
      router.push('/login');
    }
  };

  // Filter navigation based on plan features + user role + subscription gate
  const plan = (user?.plan || 'trial') as DespachoPlan;
  const role = user?.role || 'visor';
  const isOwnerSomewhere = (user?.tenants || []).some(t => t.isOwner);
  const navGate = useNavGate();
  const filteredNav = navigation.filter((item) => {
    if (item.feature && !hasDespachoFeature(plan, item.feature)) return false;
    if (item.roles && !item.roles.includes(role)) return false;
    if (item.requireOwnerSomewhere && !isOwnerSomewhere) return false;
    if (!navGate.isAllowed(item.href)) return false;
    return true;
  });

  const { data: contribuyentes } = useContribuyentes();
  const isGlobalAdmin = isGlobalAdminRfc(user?.tenantRfc, role, user?.platformRoles);
  // El admin global NO necesita "Configuración inicial" — su tenant raíz
  // (Horux 360) no tiene contribuyentes propios y nunca los tendrá.
  const showOnboarding = (!contribuyentes || contribuyentes.length === 0) && role !== 'cliente' && !isGlobalAdmin;
  const allNavigation = isGlobalAdmin
    ? [...filteredNav.slice(0, -1), ...adminNavigation, filteredNav[filteredNav.length - 1]]
    : filteredNav;

  return (
    <aside className="fixed left-0 top-0 z-40 h-screen w-64 border-r bg-card">
      <div className="flex h-full flex-col">
        {/* Logo */}
        <div className="flex h-16 items-center border-b px-6">
          <Link href="/dashboard" className="flex items-center gap-2">
            <Image
              src="/logo.jpg"
              alt="Horux Despachos"
              width={32}
              height={32}
              className="rounded-full"
            />
            <div className="flex flex-col leading-tight">
              <span className="font-bold text-xl">Horux</span>
              <span className="text-xs text-muted-foreground -mt-1">Despachos</span>
            </div>
          </Link>
        </div>

        {/* Navigation */}
        <nav className="flex-1 space-y-1 px-3 py-4">
          {showOnboarding && (
            <div className="px-3 py-2">
              <Link href="/onboarding">
                <div className="flex items-center gap-2 px-3 py-2 rounded-md bg-primary/10 text-primary text-sm font-medium hover:bg-primary/20 transition-colors">
                  <Rocket className="h-4 w-4" />
                  Configuración inicial
                </div>
              </Link>
            </div>
          )}
          {allNavigation.map((item) => {
            const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`);
            return (
              <Link
                key={item.name}
                href={item.href}
                className={cn(
                  'flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors',
                  isActive
                    ? 'bg-primary text-primary-foreground'
                    : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
                )}
              >
                <item.icon className="h-5 w-5" />
                {item.name}
              </Link>
            );
          })}
        </nav>

        {/* User & Logout — admin/TI globales no muestran nombre+email para
            mantener el sidebar más limpio (ya tienen muchos items extras) */}
        <div className="border-t p-4">
          {!isGlobalAdmin && (
            <div className="mb-3 px-3">
              <p className="text-sm font-medium">{user?.nombre}</p>
              <p className="text-xs text-muted-foreground">{user?.email}</p>
            </div>
          )}
          <button
            onClick={handleLogout}
            className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-muted-foreground hover:bg-destructive hover:text-destructive-foreground transition-colors"
          >
            <LogOut className="h-5 w-5" />
            Cerrar sesion
          </button>
        </div>
      </div>
    </aside>
  );
}
