'use client'

import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { useAuth } from '@/lib/auth'
import { useState } from 'react'
import {
  DashboardIcon,
  FolderIcon,
  BoxIcon,
  BuildingIcon,
  WarehouseIcon,
  TruckIcon,
  ArrowDownIcon,
  ArrowUpIcon,
  DocumentIcon,
  ChartIcon,
  RefreshIcon,
  DollarIcon,
  SettingsIcon,
  UsersIcon,
  WrenchIcon,
  SearchIcon,
  InventoryIcon,
  PackageIcon,
  LogoutIcon,
  PrinterIcon,
} from './Icons'

interface IconComponent {
  component: React.ComponentType<{ className?: string }>
}

interface NavItem {
  label: string
  href: string
  icon: IconComponent
  adminOnly?: boolean
  children?: { label: string; href: string; icon: IconComponent }[]
}

const navItems: NavItem[] = [
  {
    label: 'Dashboard',
    href: '/dashboard',
    icon: { component: DashboardIcon },
  },
    {
      label: 'Maestros',
      href: '/maestros',
      icon: { component: FolderIcon },
      children: [
        { label: 'Artículos', href: '/maestros/articulos', icon: { component: BoxIcon } },
        { label: 'Etiquetas', href: '/maestros/articulos/etiquetas', icon: { component: PrinterIcon } },
        { label: 'Proyectos', href: '/maestros/proyectos', icon: { component: BuildingIcon } },
        { label: 'Bodegas', href: '/maestros/bodegas', icon: { component: WarehouseIcon } },
        { label: 'Proveedores', href: '/maestros/proveedores', icon: { component: TruckIcon } },
      ],
    },
  {
    label: 'Ingresos',
    href: '/ingresos',
    icon: { component: ArrowDownIcon },
  },
  {
    label: 'Salidas',
    href: '/salidas',
    icon: { component: ArrowUpIcon },
  },
  {
    label: 'Kardex',
    href: '/kardex',
    icon: { component: DocumentIcon },
  },
  {
    label: 'Reportes',
    href: '/reportes',
    icon: { component: ChartIcon },
    children: [
      { label: 'Stock en Mano', href: '/reportes/stock', icon: { component: InventoryIcon } },
      { label: 'Movimientos', href: '/reportes/movimientos', icon: { component: RefreshIcon } },
      { label: 'Costos por Proyecto', href: '/reportes/costos', icon: { component: DollarIcon } },
      { label: 'Salidas por Proyecto', href: '/reportes/salidas-proyecto', icon: { component: ArrowUpIcon } },
    ],
  },
  {
    label: 'Configuración',
    href: '/admin',
    icon: { component: SettingsIcon },
    adminOnly: true,
    children: [
      { label: 'Usuarios', href: '/admin/usuarios', icon: { component: UsersIcon } },
      { label: 'Parámetros', href: '/admin/parametros', icon: { component: WrenchIcon } },
      { label: 'Auditoría', href: '/admin/auditoria', icon: { component: SearchIcon } },
    ],
  },
]

interface SidebarProps {
  mobileOpen?: boolean
  onMobileClose?: () => void
}

export default function Sidebar({ mobileOpen, onMobileClose }: SidebarProps) {
  const pathname = usePathname()
  const { user, logout } = useAuth()
  const [openMenus, setOpenMenus] = useState<string[]>([])
  const [collapsed, setCollapsed] = useState(false)

  const toggleMenu = (href: string) => {
    setOpenMenus((prev) =>
      prev.includes(href) ? prev.filter((m) => m !== href) : [...prev, href],
    )
  }

  const isActive = (href: string) => pathname === href
  const isParentActive = (item: NavItem) =>
    pathname.startsWith(item.href) ||
    item.children?.some((c) => pathname.startsWith(c.href))

  const filteredItems = navItems.filter(
    (item) => !item.adminOnly || user?.role === 'ADMIN',
  )

  const navContent = (
    <>
      {/* Logo */}
      <div className="flex items-center justify-between px-4 py-4 border-b border-gray-700/50">
        {!collapsed && (
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg flex items-center justify-center flex-shrink-0">
              <PackageIcon className="w-6 h-6 text-white" />
            </div>
            <div>
              <h1 className="text-base font-bold text-white leading-tight">Sistema de</h1>
              <h1 className="text-sm font-semibold text-blue-300 leading-tight">Inventario</h1>
            </div>
          </div>
        )}
        {collapsed && (
          <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg flex items-center justify-center mx-auto">
            <PackageIcon className="w-6 h-6 text-white" />
          </div>
        )}
        <button
          onClick={() => setCollapsed(!collapsed)}
          className="hidden lg:flex text-gray-400 hover:text-white hover:bg-gray-800 transition-colors p-2 rounded-lg"
          title={collapsed ? 'Expandir' : 'Colapsar'}
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            {collapsed ? (
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            ) : (
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            )}
          </svg>
        </button>
        {/* Mobile close */}
        {onMobileClose && (
          <button 
            onClick={onMobileClose} 
            className="lg:hidden text-gray-400 hover:text-white hover:bg-gray-800 transition-colors p-2 rounded-lg"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        )}
      </div>

      {/* Nav */}
      <nav className="flex-1 overflow-y-auto py-4 px-3">
        {filteredItems.map((item) => (
          <div key={item.href} className="mb-1">
            {item.children ? (
              <>
                <button
                  onClick={() => toggleMenu(item.href)}
                  className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 ${
                    isParentActive(item)
                      ? 'bg-blue-600 text-white shadow-sm'
                      : 'text-gray-300 hover:bg-gray-800/50 hover:text-white'
                  }`}
                  title={collapsed ? item.label : undefined}
                >
                  <item.icon.component className="w-5 h-5 flex-shrink-0" />
                  {!collapsed && (
                    <>
                      <span className="flex-1 text-left">{item.label}</span>
                      <svg 
                        className={`w-4 h-4 transition-transform ${openMenus.includes(item.href) || isParentActive(item) ? 'rotate-180' : ''}`}
                        fill="none" 
                        stroke="currentColor" 
                        viewBox="0 0 24 24"
                      >
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                      </svg>
                    </>
                  )}
                </button>

                {!collapsed && (openMenus.includes(item.href) || isParentActive(item)) && (
                  <div className="ml-4 mt-1 space-y-0.5 border-l-2 border-gray-700/50 pl-4 py-1">
                    {item.children.map((child) => (
                      <Link
                        key={child.href}
                        href={child.href}
                        onClick={onMobileClose}
                        className={`flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm transition-all duration-200 ${
                          isActive(child.href)
                            ? 'bg-blue-500/20 text-white font-semibold border-l-2 border-blue-400'
                            : 'text-gray-400 hover:bg-gray-800/30 hover:text-white'
                        }`}
                      >
                        <child.icon.component className="w-4 h-4 flex-shrink-0" />
                        <span>{child.label}</span>
                      </Link>
                    ))}
                  </div>
                )}
              </>
            ) : (
              <Link
                href={item.href}
                onClick={onMobileClose}
                className={`flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 ${
                  isActive(item.href)
                    ? 'bg-blue-600 text-white shadow-sm'
                    : 'text-gray-300 hover:bg-gray-800/50 hover:text-white'
                }`}
                title={collapsed ? item.label : undefined}
              >
                <item.icon.component className="w-5 h-5 flex-shrink-0" />
                {!collapsed && <span>{item.label}</span>}
              </Link>
            )}
          </div>
        ))}
      </nav>

      {/* User + Logout */}
      <div className="border-t border-gray-700/50 p-3 space-y-2">
        {!collapsed && user && (
          <div className="px-2 py-2 bg-gray-800/50 rounded-lg">
            <p className="text-xs text-white font-semibold truncate">{user.name}</p>
            <p className="text-xs text-blue-300 font-medium">{user.role}</p>
          </div>
        )}
        <button
          onClick={logout}
          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm text-gray-300 hover:bg-red-600/20 hover:text-red-300 transition-all duration-200 border border-transparent hover:border-red-600/30"
          title={collapsed ? 'Cerrar sesión' : undefined}
        >
          <LogoutIcon className="w-5 h-5 flex-shrink-0" />
          {!collapsed && <span className="font-medium">Cerrar sesión</span>}
        </button>
      </div>
    </>
  )

  return (
    <>
      {/* Desktop sidebar */}
      <aside
        className={`hidden lg:flex flex-col bg-gray-900 text-white min-h-screen flex-shrink-0 transition-all duration-300 ${
          collapsed ? 'w-16' : 'w-60'
        }`}
      >
        {navContent}
      </aside>

      {/* Mobile overlay */}
      {mobileOpen && (
        <div className="lg:hidden fixed inset-0 z-50 flex">
          <div className="absolute inset-0 bg-black bg-opacity-50" onClick={onMobileClose} />
          <aside className="relative flex flex-col bg-gray-900 text-white w-64 min-h-screen z-10">
            {navContent}
          </aside>
        </div>
      )}
    </>
  )
}
