'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { cn } from '@/lib/utils';
import {
  LayoutDashboard,
  BookOpen,
  FileText,
  Sparkles,
  BarChart3,
  ArrowLeft,
  LogOut,
  Menu,
  X,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { useAuthStore } from '@/store/useAuthStore';

interface NavLink {
  href: string;
  label: string;
  icon: React.ElementType;
}

const adminLinks: NavLink[] = [
  { href: '/admin', label: 'Dashboard', icon: LayoutDashboard },
  { href: '/admin/modules', label: 'Módulos', icon: BookOpen },
  { href: '/admin/exercises', label: 'Ejercicios', icon: FileText },
  { href: '/admin/generate', label: 'Generar IA', icon: Sparkles },
  { href: '/admin/stats', label: 'Estadísticas', icon: BarChart3 },
];

interface AdminSidebarProps {
  className?: string;
}

export function AdminSidebar({ className }: AdminSidebarProps) {
  const pathname = usePathname();
  const { logout, user } = useAuthStore();
  const [isMobileOpen, setIsMobileOpen] = useState(false);
  const [isCollapsed, setIsCollapsed] = useState(false);

  const handleLogout = () => {
    logout();
    if (typeof window !== 'undefined') {
      localStorage.removeItem('auth_token');
      window.location.href = '/login';
    }
  };

  const NavLinkComponent = ({ href, label, icon: Icon }: NavLink) => {
    const isActive = pathname === href || (href !== '/admin' && pathname.startsWith(href));
    return (
      <Link
        href={href}
        onClick={() => setIsMobileOpen(false)}
        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'
        )}
      >
        <Icon className="h-5 w-5 shrink-0" />
        {!isCollapsed && <span>{label}</span>}
      </Link>
    );
  };

  const sidebarContent = (
    <>
      {/* Logo */}
      <div className="flex h-16 items-center gap-2 border-b px-4">
        <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-destructive text-destructive-foreground">
          <span className="text-lg font-bold">⚙</span>
        </div>
        {!isCollapsed && (
          <div className="flex flex-col">
            <span className="text-sm font-semibold">Admin Panel</span>
            <span className="text-xs text-muted-foreground">Math Platform</span>
          </div>
        )}
      </div>

      {/* Navigation */}
      <nav className="flex-1 space-y-1 overflow-y-auto p-3">
        <div className="space-y-1">
          {adminLinks.map((link) => (
            <NavLinkComponent key={link.href} {...link} />
          ))}
        </div>

        <Separator className="my-3" />

        <Link
          href="/dashboard"
          className="flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-colors"
        >
          <ArrowLeft className="h-5 w-5 shrink-0" />
          {!isCollapsed && <span>Volver al sitio</span>}
        </Link>
      </nav>

      {/* User section */}
      <div className="border-t p-3">
        <div className="flex items-center gap-3">
          <div className="flex h-9 w-9 items-center justify-center rounded-full bg-destructive/10 text-destructive">
            {user?.username?.[0]?.toUpperCase() ?? 'A'}
          </div>
          {!isCollapsed && (
            <div className="flex min-w-0 flex-1 flex-col">
              <span className="truncate text-sm font-medium">
                {user?.username ?? 'Admin'}
              </span>
              <span className="truncate text-xs text-muted-foreground">
                Administrador
              </span>
            </div>
          )}
        </div>
        <Button
          variant="ghost"
          size="sm"
          className="mt-2 w-full justify-start text-muted-foreground"
          onClick={handleLogout}
        >
          <LogOut className="mr-2 h-4 w-4" />
          {!isCollapsed && 'Cerrar sesión'}
        </Button>
      </div>

      {/* Collapse toggle */}
      <Button
        variant="ghost"
        size="icon"
        className="absolute -right-3 top-20 hidden h-6 w-6 rounded-full border bg-background md:flex"
        onClick={() => setIsCollapsed(!isCollapsed)}
      >
        {isCollapsed ? (
          <Menu className="h-3 w-3" />
        ) : (
          <X className="h-3 w-3" />
        )}
      </Button>
    </>
  );

  return (
    <>
      {/* Mobile backdrop */}
      {isMobileOpen && (
        <div
          className="fixed inset-0 z-40 bg-black/50 md:hidden"
          onClick={() => setIsMobileOpen(false)}
          onKeyDown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              setIsMobileOpen(false);
            }
          }}
          role="button"
          tabIndex={0}
          aria-label="Cerrar menú móvil"
        />
      )}

      {/* Mobile sidebar */}
      <aside
        className={cn(
          'fixed inset-y-0 left-0 z-50 w-64 transform bg-background md:hidden',
          isMobileOpen ? 'translate-x-0' : '-translate-x-full',
          'transition-transform duration-300 ease-in-out'
        )}
      >
        {sidebarContent}
      </aside>

      {/* Desktop sidebar */}
      <aside
        className={cn(
          'hidden md:flex md:flex-col',
          isCollapsed ? 'w-16' : 'w-64',
          'border-r bg-background',
          'transition-all duration-300',
          className
        )}
      >
        {sidebarContent}
      </aside>

      {/* Mobile toggle button */}
      <Button
        variant="ghost"
        size="icon"
        className="md:hidden"
        onClick={() => setIsMobileOpen(true)}
      >
        <Menu className="h-5 w-5" />
      </Button>
    </>
  );
}