'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,
  Scale,
  Send,
} from 'lucide-react';
import { useAuthStore } from '@/stores/auth-store';
import { logout } from '@/lib/api/auth';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { hasFeature, isGlobalAdminRfc, type Plan } from '@horux/shared';

const navigation = [
  { name: 'Dashboard', href: '/dashboard', icon: LayoutDashboard, roles: ['owner', 'contador'] },
  { name: 'CFDI', href: '/cfdi', icon: FileText },
  { name: 'Impuestos', href: '/impuestos', icon: Calculator },
  { name: 'Reportes', href: '/reportes', icon: BarChart3, feature: 'reportes', roles: ['owner'] },
  { 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', 'contador'] },
  { name: 'Usuarios', href: '/usuarios', icon: Users, roles: ['owner'] },
  { name: 'Configuración', href: '/configuracion', icon: Settings, roles: ['owner'] },
] as const;

const adminNavigation = [
  { name: 'Clientes', href: '/clientes', icon: Building2 },
];

export function SidebarCompact() {
  const pathname = usePathname();
  const router = useRouter();
  const { user, logout: clearAuth } = useAuthStore();
  const [expanded, setExpanded] = useState(false);

  const plan = (user?.plan || 'starter') as Plan;
  const role = user?.role || 'visor';
  const filteredNav = navigation.filter((item) => {
    if ('feature' in item && item.feature && !hasFeature(plan, item.feature)) return false;
    if ('roles' in item && item.roles && !item.roles.includes(role as any)) return false;
    return true;
  });

  const isGlobalAdmin = isGlobalAdminRfc(user?.tenantRfc, role, user?.platformRoles);
  const allNavigation = isGlobalAdmin
    ? [...filteredNav.slice(0, -1), ...adminNavigation, filteredNav[filteredNav.length - 1]].filter(Boolean)
    : filteredNav;

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

  return (
    <aside
      className={cn(
        'fixed left-0 top-0 z-40 h-screen border-r bg-card transition-all duration-300',
        expanded ? 'w-64' : 'w-16'
      )}
      onMouseEnter={() => setExpanded(true)}
      onMouseLeave={() => setExpanded(false)}
    >
      <div className="flex h-full flex-col">
        {/* Logo */}
        <div className="flex h-14 items-center border-b px-4">
          <Link href="/dashboard" className="flex items-center gap-2">
            <Image
              src="/logo.jpg"
              alt="Horux Despachos"
              width={32}
              height={32}
              className="rounded-full flex-shrink-0"
            />
            <span className={cn(
              'font-bold text-lg whitespace-nowrap transition-opacity duration-300',
              expanded ? 'opacity-100' : 'opacity-0 w-0 overflow-hidden'
            )}>
              Horux Despachos
            </span>
          </Link>
        </div>

        {/* Navigation */}
        <nav className="flex-1 space-y-1 px-2 py-3">
          {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 px-2 py-2 text-sm font-medium transition-colors',
                  isActive
                    ? 'bg-primary text-primary-foreground'
                    : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
                )}
                title={!expanded ? item.name : undefined}
              >
                <item.icon className="h-5 w-5 flex-shrink-0" />
                <span className={cn(
                  'whitespace-nowrap transition-opacity duration-300',
                  expanded ? 'opacity-100' : 'opacity-0 w-0 overflow-hidden'
                )}>
                  {item.name}
                </span>
              </Link>
            );
          })}
        </nav>

        {/* User & Logout */}
        <div className="border-t p-2">
          {expanded && (
            <div className="mb-2 px-2 py-1">
              <p className="text-xs font-medium truncate">{user?.nombre}</p>
              <p className="text-xs text-muted-foreground truncate">{user?.email}</p>
            </div>
          )}
          <button
            onClick={handleLogout}
            className={cn(
              'flex w-full items-center gap-3 rounded px-2 py-2 text-sm font-medium text-muted-foreground hover:bg-destructive hover:text-destructive-foreground transition-colors'
            )}
            title={!expanded ? 'Cerrar sesión' : undefined}
          >
            <LogOut className="h-5 w-5 flex-shrink-0" />
            <span className={cn(
              'whitespace-nowrap transition-opacity duration-300',
              expanded ? 'opacity-100' : 'opacity-0 w-0 overflow-hidden'
            )}>
              Cerrar sesión
            </span>
          </button>
        </div>
      </div>
    </aside>
  );
}
