import React from 'react';
import { 
  LayoutDashboard, 
  ArrowRightLeft, 
  CreditCard, 
  Wallet, 
  PieChart, 
  FileText,
  ShieldCheck,
  Settings,
  Users,
  Building,
  ChevronDown,
  LogOut,
  ChevronLeft,
  Truck
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';

export const FinanceiroV2Sidebar = ({ currentView, onViewChange, onLogout, isCollapsed = false }) => {
  const [expandedGroups, setExpandedGroups] = React.useState({
    financeiro: true,
    rh: false,
    frota: false,
    admin: false
  });

  const toggleGroup = (groupId) => {
    if (isCollapsed) return; // Não expande grupos quando colapsado
    setExpandedGroups(prev => ({ ...prev, [groupId]: !prev[groupId] }));
  };

  const navStructure = [
    {
      type: 'single',
      id: 'dashboard',
      label: 'Dashboard',
      icon: LayoutDashboard,
      highlight: true
    },
    {
      type: 'group',
      id: 'financeiro',
      label: 'Financeiro',
      icon: Wallet,
      items: [
        { id: 'fluxo', label: 'Fluxo de Caixa', icon: ArrowRightLeft },
        { id: 'pagar', label: 'Contas a Pagar', icon: CreditCard },
        { id: 'receber', label: 'Contas a Receber', icon: Wallet },
        { id: 'conciliacao', label: 'Conciliação', icon: ShieldCheck },
        { id: 'relatorios', label: 'Relatórios', icon: FileText },
      ]
    },
    {
      type: 'group',
      id: 'rh',
      label: 'RH',
      icon: Users,
      items: [
        { id: 'ponto', label: 'Bater Ponto' },
        { id: 'gestao-rh', label: 'Gestão de Equipe' },
      ]
    },
    {
      type: 'group',
      id: 'frota',
      label: 'Gestão de Frota',
      icon: Truck,
      items: [
        { id: 'frota-overview', label: 'Visão Geral' },
        { id: 'frota-veiculos', label: 'Veículos' },
        { id: 'frota-abastecimento', label: 'Abastecimento' },
        { id: 'frota-manutencao', label: 'Manutenção' },
        { id: 'frota-pneus', label: 'Gestão de Pneus' },
        { id: 'frota-multas', label: 'Multas' },
      ]
    },
    {
      type: 'group',
      id: 'admin',
      label: 'Administrativo',
      icon: Building,
      items: [
        { id: 'admin-clientes', label: 'Clientes' },
      ]
    }
  ];

  return (
    <nav className="flex-1 space-y-2 py-4 px-2 scrollbar-none">
      {navStructure.map((item) => {
        if (item.type === 'single') {
          return (
            <Button
              key={item.id}
              variant="ghost"
              className={cn(
                "w-full h-12 rounded-xl transition-all duration-300 group relative overflow-hidden mb-2",
                isCollapsed ? "justify-center px-2" : "justify-start gap-4 px-4",
                item.highlight
                  ? "bg-emerald-600 text-white shadow-lg shadow-emerald-500/20 font-black hover:bg-emerald-500 hover:scale-[1.02]" 
                  : cn(
                      "text-slate-500 hover:text-slate-200 hover:bg-slate-800/50",
                      currentView === item.id && "bg-slate-800 text-white font-bold"
                    )
              )}
              onClick={() => onViewChange(item.id)}
              title={isCollapsed ? item.label : undefined}
            >
              <item.icon size={20} className={cn("transition-colors duration-300 shrink-0", item.highlight ? "text-white" : "text-slate-400 group-hover:text-emerald-500")} />
              {!isCollapsed && <span className="truncate text-sm tracking-tight">{item.label}</span>}
            </Button>
          );
        }

        const isExpanded = expandedGroups[item.id];
        const isActiveGroup = item.items.some(sub => sub.id === currentView);

        return (
          <div key={item.id} className="space-y-1 mb-2">
            <button
              onClick={() => toggleGroup(item.id)}
              className={cn(
                "w-full flex items-center rounded-xl transition-all duration-300 group text-slate-500 hover:text-slate-200 hover:bg-slate-800/50",
                isCollapsed ? "justify-center px-2 py-3" : "justify-between px-4 py-3",
                isActiveGroup && !isExpanded && "text-emerald-500 bg-emerald-500/5 border-l-2 border-emerald-500 rounded-l-none"
              )}
              title={isCollapsed ? item.label : undefined}
            >
            <div className={cn("flex items-center text-[10px] font-bold uppercase tracking-[0.15em]", isCollapsed ? "justify-center" : "gap-4")}>
              <item.icon size={16} className={cn("transition-colors duration-300", isActiveGroup ? "text-emerald-500" : "text-slate-500 group-hover:text-emerald-400")} />
              {!isCollapsed && <span className="font-bold">{item.label}</span>}
            </div>
            {!isCollapsed && <ChevronDown className={cn("w-3.5 h-3.5 transition-transform duration-300 text-slate-600 group-hover:text-slate-400", isExpanded ? "rotate-180" : "rotate-0")} strokeWidth={3} />}
            </button>

            {!isCollapsed && isExpanded && (
              <div className="ml-4 pl-6 border-l border-slate-100 space-y-1 mt-1">
                {item.items.map(subItem => {
                   const isActive = currentView === subItem.id;
                   return (
                      <button
                        key={subItem.id}
                        onClick={() => onViewChange(subItem.id)}
                        className={cn(
                          "w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-xs transition-all duration-300 text-left relative group",
                          isActive
                            ? "text-emerald-500 font-black bg-emerald-500/5"
                            : "text-slate-500 hover:text-slate-200 hover:bg-slate-800/30"
                        )}
                      >
                        {isActive && <div className="absolute left-0 w-1 h-3 bg-emerald-500 rounded-full -ml-[25px]" />}
                        {subItem.label}
                      </button>
                   );
                })}
              </div>
            )}
          </div>
        );
      })}

      <div className="pt-8 mt-8 border-t border-slate-100">
        <button
          onClick={onLogout}
          className={cn(
            "w-full flex items-center h-12 rounded-xl text-slate-400 hover:text-rose-600 hover:bg-rose-50 transition-all duration-300 group",
            isCollapsed ? "justify-center px-2" : "gap-4 px-4"
          )}
          title={isCollapsed ? "Sair" : undefined}
        >
          <LogOut size={20} className="text-slate-300 group-hover:text-rose-600 transition-colors" />
          {!isCollapsed && <span className="text-sm font-bold uppercase tracking-widest">Sair</span>}
        </button>
      </div>
    </nav>
  );
};
