import { Link, useLocation } from 'react-router-dom'
import {
  LayoutDashboard,
  ShoppingCart,
  Calculator,
  Zap,
  Settings,
  UserPlus,
  Users,
  ShieldCheck,
  KeyRound,
  FileClock,
  PanelLeftClose,
  PanelLeftOpen,
  Newspaper,
  Columns3,
  Store,
  Tag,
  Layers,
  Package,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { Badge } from '@/components/ui/badge'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { useAuthStore } from '@/stores/authStore'
import { useSidebar } from '@/hooks/useSidebar'

interface NavItem {
  label: string
  href: string
  icon: React.ElementType
  disabled?: boolean
  /** Si se define, el item solo se muestra si el user tiene este permiso. */
  requiredPermission?: string
}

const navItems: NavItem[] = [
  { label: 'Dashboard', href: '/', icon: LayoutDashboard },
  { label: 'Ventas', href: '/ventas', icon: ShoppingCart, disabled: true },
  { label: 'Tasación', href: '/tasacion', icon: Calculator, disabled: true },
  { label: 'Integraciones', href: '/integraciones', icon: Zap, disabled: true },
  { label: 'Administración', href: '/administracion', icon: Settings, disabled: true },
]

const adminItems: NavItem[] = [
  { label: 'Usuarios', href: '/usuarios', icon: Users },
  { label: 'Crear Usuario', href: '/usuarios/nuevo', icon: UserPlus },
  { label: 'Roles', href: '/admin/roles', icon: ShieldCheck },
  { label: 'Permisos', href: '/admin/permisos', icon: KeyRound },
  {
    label: 'Auditoría',
    href: '/admin/audit',
    icon: FileClock,
    requiredPermission: 'administracion:auditoria:ver',
  },
  {
    label: 'Medios',
    href: '/admin/medios',
    icon: Newspaper,
    requiredPermission: 'administracion:medios:gestionar',
  },
  {
    label: 'Secciones',
    href: '/admin/secciones',
    icon: Columns3,
    requiredPermission: 'administracion:secciones:gestionar',
  },
  {
    label: 'Puntos de Venta',
    href: '/admin/puntos-de-venta',
    icon: Store,
    requiredPermission: 'administracion:puntos_de_venta:gestionar',
  },
  {
    label: 'Rubros',
    href: '/admin/rubros',
    icon: Tag,
    requiredPermission: 'catalogo:rubros:gestionar',
  },
  {
    label: 'Tipos de Producto',
    href: '/admin/product-types',
    icon: Layers,
    requiredPermission: 'catalogo:tipos:gestionar',
  },
  {
    label: 'Productos',
    href: '/admin/products',
    icon: Package,
    requiredPermission: 'catalogo:productos:gestionar',
  },
]

interface SidebarNavProps {
  /** When true forces expanded layout regardless of persisted state — used by mobile Sheet. */
  forceExpanded?: boolean
}

export function SidebarNav({ forceExpanded = false }: SidebarNavProps) {
  const { pathname } = useLocation()
  const user = useAuthStore((s) => s.user)
  const isAdmin = user?.rol === 'admin'
  const { collapsed: persisted, toggle } = useSidebar()
  const collapsed = forceExpanded ? false : persisted

  function isItemActive(item: NavItem): boolean {
    if (item.disabled) return false
    if (item.href === '/') return pathname === '/'
    if (item.href === '/usuarios') {
      return pathname.startsWith('/usuarios') && pathname !== '/usuarios/nuevo'
    }
    if (item.href === '/usuarios/nuevo') return pathname === '/usuarios/nuevo'
    return pathname.startsWith(item.href)
  }

  return (
    <aside
      className={cn(
        'flex h-full flex-col bg-card text-card-foreground transition-[width] duration-200 ease-out',
        collapsed ? 'w-[68px]' : 'w-60',
      )}
      data-collapsed={collapsed}
    >
      {/* Brand + Toggle (top header) */}
      <div
        className={cn(
          'flex h-14 items-center border-b border-border shrink-0',
          collapsed ? 'justify-center px-2' : 'px-3 gap-2',
        )}
      >
        {!forceExpanded && (
          <Tooltip>
            <TooltipTrigger asChild>
              <button
                type="button"
                onClick={toggle}
                aria-label={collapsed ? 'Expandir sidebar' : 'Colapsar sidebar'}
                className="flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground shrink-0"
              >
                {collapsed ? (
                  <PanelLeftOpen className="h-4 w-4" />
                ) : (
                  <PanelLeftClose className="h-4 w-4" />
                )}
              </button>
            </TooltipTrigger>
            <TooltipContent side="right">
              {collapsed ? 'Expandir' : 'Colapsar'}
            </TooltipContent>
          </Tooltip>
        )}

        {!collapsed && (
          <span className="text-sm font-semibold tracking-tight text-foreground truncate">
            SIG-CM 2.0
          </span>
        )}
      </div>

      {/* Nav */}
      <nav className="flex-1 overflow-y-auto overflow-x-hidden py-3 px-2 space-y-1">
        {navItems.map((item) => (
          <NavRow
            key={item.href}
            item={item}
            collapsed={collapsed}
            active={isItemActive(item)}
          />
        ))}

        {isAdmin && (
          <>
            <SectionLabel collapsed={collapsed}>Administración</SectionLabel>
            {adminItems
              .filter(
                (item) =>
                  !item.requiredPermission ||
                  user?.permisos.includes(item.requiredPermission),
              )
              .map((item) => (
                <NavRow
                  key={item.href}
                  item={item}
                  collapsed={collapsed}
                  active={isItemActive(item)}
                />
              ))}
          </>
        )}
      </nav>
    </aside>
  )
}

/* ────────────────────────────────────────────────────────────────
   Sub-componentes
   ──────────────────────────────────────────────────────────────── */

interface NavRowProps {
  item: NavItem
  collapsed: boolean
  active: boolean
}

function NavRow({ item, collapsed, active }: NavRowProps) {
  const Icon = item.icon

  const baseClasses = cn(
    'relative flex items-center rounded-md text-sm transition-colors',
    collapsed ? 'justify-center h-10 w-10 mx-auto' : 'gap-3 px-3 py-2',
  )

  // Disabled item
  if (item.disabled) {
    const content = (
      <div
        className={cn(
          baseClasses,
          'text-muted-foreground/70 cursor-not-allowed opacity-60',
        )}
        aria-disabled="true"
      >
        <Icon className="h-4 w-4 shrink-0" />
        {!collapsed && (
          <>
            <span className="flex-1 truncate">{item.label}</span>
            <Badge variant="secondary" className="text-[10px] px-1.5 py-0 shrink-0">
              Próx.
            </Badge>
          </>
        )}
      </div>
    )

    if (!collapsed) return content
    return (
      <Tooltip>
        <TooltipTrigger asChild>{content}</TooltipTrigger>
        <TooltipContent side="right">
          {item.label}{' '}
          <span className="text-muted-foreground">· Próximamente</span>
        </TooltipContent>
      </Tooltip>
    )
  }

  // Active link
  const link = (
    <Link
      to={item.href}
      className={cn(
        baseClasses,
        active
          ? 'bg-accent text-accent-foreground font-medium'
          : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
      )}
      aria-current={active ? 'page' : undefined}
    >
      {/* Active indicator bar (left edge) when expanded */}
      {active && !collapsed && (
        <span className="absolute left-0 top-1/2 -translate-y-1/2 h-5 w-0.5 rounded-r-full bg-primary" />
      )}
      <Icon className="h-4 w-4 shrink-0" />
      {!collapsed && <span className="truncate">{item.label}</span>}
    </Link>
  )

  if (!collapsed) return link
  return (
    <Tooltip>
      <TooltipTrigger asChild>{link}</TooltipTrigger>
      <TooltipContent side="right">{item.label}</TooltipContent>
    </Tooltip>
  )
}

function SectionLabel({
  collapsed,
  children,
}: {
  collapsed: boolean
  children: React.ReactNode
}) {
  if (collapsed) {
    return <div className="my-2 mx-2 border-t border-border" aria-hidden="true" />
  }
  return (
    <div className="pt-3 pb-1 px-3">
      <span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/60">
        {children}
      </span>
    </div>
  )
}
