import { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
import { modules, type NavModule } from '@/config/navigation';
import { Button } from '@/components/ui/button';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@/components/ui/tooltip';

interface AppSidebarProps {
  collapsed: boolean;
  onToggle: () => void;
}

export function AppSidebar({ collapsed, onToggle }: AppSidebarProps) {
  const location = useLocation();
  const [expandedModules, setExpandedModules] = useState<string[]>(['dashboard', 'rh']);

  const toggleModule = (moduleId: string) => {
    setExpandedModules((prev) =>
      prev.includes(moduleId)
        ? prev.filter((id) => id !== moduleId)
        : [...prev, moduleId]
    );
  };

  const isActive = (href: string) => location.pathname === href;
  const isModuleActive = (module: NavModule) =>
    module.items.some((item) => location.pathname.startsWith(item.href));

  return (
    <>
      {/* Mobile overlay */}
      <div
        className={cn(
          'fixed inset-0 bg-foreground/50 z-40 lg:hidden transition-opacity',
          collapsed ? 'opacity-0 pointer-events-none' : 'opacity-100'
        )}
        onClick={onToggle}
      />

      {/* Sidebar */}
      <aside
        className={cn(
          'fixed top-0 left-0 z-50 h-screen bg-sidebar text-sidebar-foreground',
          'flex flex-col transition-all duration-300 ease-in-out',
          'border-r border-sidebar-border',
          collapsed ? 'w-16' : 'w-64',
          'lg:translate-x-0',
          collapsed ? '-translate-x-full lg:translate-x-0' : 'translate-x-0'
        )}
      >
        {/* Logo */}
        <div className="flex h-16 items-center justify-between px-4 border-b border-sidebar-border">
          {!collapsed && (
            <Link to="/" className="flex items-center gap-2">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground font-bold">
                S
              </div>
              <div className="flex flex-col">
                <span className="text-sm font-semibold">SIGEP</span>
                <span className="text-[10px] text-sidebar-muted leading-tight">
                  Sistema de Gestão
                </span>
              </div>
            </Link>
          )}

          {collapsed && (
            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground font-bold mx-auto">
              S
            </div>
          )}
        </div>

        {/* Navigation */}
        <nav className="flex-1 overflow-y-auto py-4 px-2">
          {modules.map((module) => (
            <div key={module.id} className="mb-1">
              {collapsed ? (
                <Tooltip delayDuration={0}>
                  <TooltipTrigger asChild>
                    <Link
                      to={module.items[0].href}
                      className={cn(
                        'flex items-center justify-center h-10 w-full rounded-lg',
                        'transition-colors duration-200',
                        isModuleActive(module)
                          ? 'bg-sidebar-accent text-sidebar-primary'
                          : 'text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground'
                      )}
                    >
                      <module.icon className="h-5 w-5" />
                    </Link>
                  </TooltipTrigger>
                  <TooltipContent side="right" className="font-medium">
                    {module.name}
                  </TooltipContent>
                </Tooltip>
              ) : (
                <>
                  {module.items.length === 1 ? (
                    <Link
                      to={module.items[0].href}
                      className={cn(
                        'flex items-center justify-between w-full px-3 py-2 rounded-lg',
                        'text-sm font-medium transition-colors duration-200',
                        isModuleActive(module)
                          ? 'bg-sidebar-accent text-sidebar-primary'
                          : 'text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground'
                      )}
                    >
                      <div className="flex items-center gap-3">
                        <module.icon className="h-5 w-5" />
                        <span>{module.name}</span>
                      </div>
                    </Link>
                  ) : (
                    <>
                      <button
                        onClick={() => toggleModule(module.id)}
                        className={cn(
                          'flex items-center justify-between w-full px-3 py-2 rounded-lg',
                          'text-sm font-medium transition-colors duration-200',
                          isModuleActive(module)
                            ? 'bg-sidebar-accent text-sidebar-primary'
                            : 'text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground'
                        )}
                      >
                        <div className="flex items-center gap-3">
                          <module.icon className="h-5 w-5" />
                          <span>{module.name}</span>
                        </div>
                        <ChevronDown
                          className={cn(
                            'h-4 w-4 transition-transform duration-200',
                            expandedModules.includes(module.id) && 'rotate-180'
                          )}
                        />
                      </button>

                      {/* Submenu */}
                      {expandedModules.includes(module.id) && (
                        <div className="mt-1 ml-4 pl-4 border-l border-sidebar-border space-y-1">
                          {module.items.map((item) => (
                            <Link
                              key={item.href}
                              to={item.href}
                              className={cn(
                                'flex items-center gap-3 px-3 py-2 rounded-lg text-sm',
                                'transition-colors duration-200',
                                isActive(item.href)
                                  ? 'bg-sidebar-primary text-sidebar-primary-foreground'
                                  : 'text-sidebar-muted hover:bg-sidebar-accent hover:text-sidebar-accent-foreground'
                              )}
                            >
                              <item.icon className="h-4 w-4" />
                              <span>{item.name}</span>
                              {item.badge && (
                                <span className="ml-auto text-xs bg-sidebar-primary text-sidebar-primary-foreground px-2 py-0.5 rounded-full">
                                  {item.badge}
                                </span>
                              )}
                            </Link>
                          ))}
                        </div>
                      )}
                    </>
                  )}
                </>
              )}
            </div>
          ))}
        </nav>

        {/* Collapse button */}
        <div className="p-2 border-t border-sidebar-border">
          <Button
            variant="ghost"
            size="sm"
            onClick={onToggle}
            className="w-full justify-center text-sidebar-muted hover:text-sidebar-foreground hover:bg-sidebar-accent"
          >
            {collapsed ? (
              <ChevronRight className="h-4 w-4" />
            ) : (
              <>
                <ChevronLeft className="h-4 w-4 mr-2" />
                <span>Recolher</span>
              </>
            )}
          </Button>
        </div>
      </aside>
    </>
  );
}
