'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { cn } from '@/lib/utils'
import { useAuth } from '@/lib/auth-context'
import type { UserRole } from '@/lib/types'
import {
  LayoutDashboard,
  Building2,
  Users,
  ShieldCheck,
  Settings,
  ScrollText,
  RefreshCw,
  UserCog,
  UsersRound,
  ChevronLeft,
  ChevronRight,
  ChevronDown,
  LogOut,
  Server,
  Bot,
  SlidersHorizontal,
  Fingerprint,
} from 'lucide-react'
import useSWR from 'swr'

// ─── Módulos disponíveis no sistema ──────────────────────────────────────────
export const AVAILABLE_MODULES = [
  {
    id: 'identity',
    label: 'Identidade (AD)',
    description: 'Usuários, grupos e sincronização com Active Directory',
  },
] as const

export type ModuleId = (typeof AVAILABLE_MODULES)[number]['id']

// ─── Estrutura de navegação ───────────────────────────────────────────────────
interface NavItem {
  label: string
  href: string
  icon: React.ElementType
  roles: UserRole[]
  module?: ModuleId
}

// Itens de nível superior: podem ser links diretos ou menus com submenus
interface NavMenu {
  id: string
  label: string
  icon: React.ElementType
  // Se definido, é um link direto (sem submenu)
  href?: string
  roles: UserRole[]
  // Se definido, é um menu com submenus
  children?: NavItem[]
}

const NAV: NavMenu[] = [
  {
    id: 'dashboard',
    label: 'Dashboard',
    href: '/dashboard',
    icon: LayoutDashboard,
    roles: ['admin_global', 'tenant_admin', 'tenant_operator', 'tenant_viewer'],
  },
  {
    id: 'admin',
    label: 'Administração',
    icon: SlidersHorizontal,
    roles: ['admin_global', 'tenant_admin'],
    children: [
      {
        label: 'Empresas',
        href: '/tenants',
        icon: Building2,
        roles: ['admin_global'],
      },
      {
        label: 'Usuários do Portal',
        href: '/portal-users',
        icon: Users,
        roles: ['admin_global', 'tenant_admin'],
      },
      {
        label: 'Permissões',
        href: '/permissions',
        icon: ShieldCheck,
        roles: ['admin_global', 'tenant_admin'],
      },
      {
        label: 'Auditoria',
        href: '/audit',
        icon: ScrollText,
        roles: ['admin_global', 'tenant_admin'],
      },
      {
        label: 'Configurações',
        href: '/tenant-config',
        icon: Settings,
        roles: ['tenant_admin'],
      },
      {
        label: 'Agente',
        href: '/agent',
        icon: Bot,
        roles: ['admin_global', 'tenant_admin'],
      },
    ],
  },
  {
    id: 'identity',
    label: 'Identidade',
    icon: Fingerprint,
    roles: ['admin_global', 'tenant_admin', 'tenant_operator', 'tenant_viewer'],
    children: [
      {
        label: 'Usuários AD',
        href: '/ad/users',
        icon: UserCog,
        roles: ['admin_global', 'tenant_admin', 'tenant_operator', 'tenant_viewer'],
        module: 'identity',
      },
      {
        label: 'Grupos AD',
        href: '/ad/groups',
        icon: UsersRound,
        roles: ['admin_global', 'tenant_admin', 'tenant_operator'],
        module: 'identity',
      },
      {
        label: 'Sincronização',
        href: '/sync',
        icon: RefreshCw,
        roles: ['admin_global', 'tenant_admin'],
        module: 'identity',
      },
    ],
  },
]

function getRoleLabel(role: UserRole | undefined): string {
  switch (role) {
    case 'admin_global':    return 'Admin Global'
    case 'tenant_admin':    return 'Admin da Empresa'
    case 'tenant_operator': return 'Operador'
    case 'tenant_viewer':   return 'Visualizador'
    default:                return 'Portal'
  }
}

export function Sidebar() {
  const pathname = usePathname()
  const { user, logout } = useAuth()
  const [collapsed, setCollapsed] = useState(false)
  // Controla quais menus com submenus estão abertos (id do menu)
  const [openMenus, setOpenMenus] = useState<Record<string, boolean>>({})

  const role = (user?.role ?? 'tenant_viewer') as UserRole
  const tenantId = user?.tenantId

  // Busca módulos habilitados do tenant
  const { data: tenantData } = useSWR(
    tenantId && role !== 'admin_global' ? `/api/tenants/${tenantId}` : null,
    (url: string) =>
      fetch(url, {
        headers: {
          Authorization: `Bearer ${typeof window !== 'undefined' ? sessionStorage.getItem('adm_token') ?? '' : ''}`,
        },
      }).then((r) => (r.ok ? r.json() : null)),
  )

  const enabledModules: string[] =
    role === 'admin_global'
      ? AVAILABLE_MODULES.map((m) => m.id)
      : (() => {
          try {
            const raw = tenantData?.enabled_modules
            if (!raw) return []
            return typeof raw === 'string' ? JSON.parse(raw) : (raw as string[])
          } catch {
            return []
          }
        })()

  // Abre automaticamente o menu pai se algum filho estiver ativo
  useEffect(() => {
    const auto: Record<string, boolean> = {}
    NAV.forEach((menu) => {
      if (menu.children) {
        const hasActive = menu.children.some(
          (item) => pathname === item.href || pathname.startsWith(item.href + '/'),
        )
        if (hasActive) auto[menu.id] = true
      }
    })
    setOpenMenus((prev) => ({ ...prev, ...auto }))
  }, [pathname])

  function toggleMenu(id: string) {
    setOpenMenus((prev) => ({ ...prev, [id]: !prev[id] }))
  }

  async function handleLogout() {
    await logout()
    window.location.href = '/login'
  }

  function isItemVisible(item: NavItem): boolean {
    if (!(item.roles as string[]).includes(role)) return false
    if (item.module && !enabledModules.includes(item.module)) return false
    return true
  }

  if (!user) return null

  return (
    <aside
      className={cn(
        'flex flex-col h-screen bg-sidebar text-sidebar-foreground border-r border-sidebar-border transition-all duration-200 shrink-0',
        collapsed ? 'w-16' : 'w-56',
      )}
    >
      {/* Logo */}
      <div className="flex items-center gap-3 px-4 h-14 border-b border-sidebar-border shrink-0">
        <div className="flex items-center justify-center w-7 h-7 rounded-lg bg-primary shrink-0">
          <Server className="w-3.5 h-3.5 text-primary-foreground" />
        </div>
        {!collapsed && (
          <div className="flex flex-col min-w-0">
            <span className="text-sm font-bold text-sidebar-foreground truncate leading-tight">ConsultarTI</span>
            <span className="text-[10px] text-sidebar-foreground/50 truncate">Portal de Serviços</span>
          </div>
        )}
        <button
          onClick={() => setCollapsed((c) => !c)}
          className="ml-auto p-1 rounded hover:bg-sidebar-accent transition-colors shrink-0"
          aria-label={collapsed ? 'Expandir menu' : 'Recolher menu'}
        >
          {collapsed ? (
            <ChevronRight className="w-3.5 h-3.5 text-sidebar-foreground/50" />
          ) : (
            <ChevronLeft className="w-3.5 h-3.5 text-sidebar-foreground/50" />
          )}
        </button>
      </div>

      {/* Nav */}
      <nav className="flex-1 overflow-y-auto py-2 px-2 space-y-0.5">
        {NAV.map((menu) => {
          // Verifica se o usuário tem acesso ao menu
          if (!(menu.roles as string[]).includes(role)) return null

          const Icon = menu.icon

          // Item de link direto (sem submenu)
          if (menu.href) {
            const isActive = pathname === menu.href || pathname.startsWith(menu.href + '/')
            return (
              <Link
                key={menu.id}
                href={menu.href}
                className={cn(
                  'flex items-center gap-2.5 px-2 py-2 rounded-md text-sm transition-colors',
                  isActive
                    ? 'bg-sidebar-primary text-sidebar-primary-foreground font-medium'
                    : 'text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
                  collapsed && 'justify-center',
                )}
                title={collapsed ? menu.label : undefined}
              >
                <Icon className="w-4 h-4 shrink-0" />
                {!collapsed && <span className="truncate">{menu.label}</span>}
              </Link>
            )
          }

          // Menu com submenus
          const visibleChildren = (menu.children ?? []).filter(isItemVisible)
          if (visibleChildren.length === 0) return null

          const isOpen = openMenus[menu.id] ?? false
          const hasActiveChild = visibleChildren.some(
            (item) => pathname === item.href || pathname.startsWith(item.href + '/'),
          )

          return (
            <div key={menu.id}>
              {/* Cabeçalho do menu */}
              <button
                onClick={() => !collapsed && toggleMenu(menu.id)}
                className={cn(
                  'w-full flex items-center gap-2.5 px-2 py-2 rounded-md text-sm transition-colors',
                  hasActiveChild && !isOpen
                    ? 'text-sidebar-foreground font-medium'
                    : 'text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
                  collapsed && 'justify-center',
                )}
                title={collapsed ? menu.label : undefined}
                aria-expanded={isOpen}
              >
                <Icon className="w-4 h-4 shrink-0" />
                {!collapsed && (
                  <>
                    <span className="truncate flex-1 text-left">{menu.label}</span>
                    <ChevronDown
                      className={cn(
                        'w-3.5 h-3.5 shrink-0 transition-transform duration-200 text-sidebar-foreground/40',
                        isOpen && 'rotate-180',
                      )}
                    />
                  </>
                )}
              </button>

              {/* Submenus */}
              {!collapsed && isOpen && (
                <ul className="mt-0.5 ml-3 pl-2 border-l border-sidebar-border space-y-0.5">
                  {visibleChildren.map((item) => {
                    const isActive =
                      pathname === item.href || pathname.startsWith(item.href + '/')
                    const SubIcon = item.icon
                    return (
                      <li key={item.href}>
                        <Link
                          href={item.href}
                          className={cn(
                            'flex items-center gap-2 px-2 py-1.5 rounded-md text-sm transition-colors',
                            isActive
                              ? 'bg-sidebar-primary text-sidebar-primary-foreground font-medium'
                              : 'text-sidebar-foreground/60 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
                          )}
                        >
                          <SubIcon className="w-3.5 h-3.5 shrink-0" />
                          <span className="truncate">{item.label}</span>
                        </Link>
                      </li>
                    )
                  })}
                </ul>
              )}

              {/* Modo collapsed: mostra submenus como ícones diretos */}
              {collapsed && (
                <div className="space-y-0.5 mt-0.5">
                  {visibleChildren.map((item) => {
                    const isActive =
                      pathname === item.href || pathname.startsWith(item.href + '/')
                    const SubIcon = item.icon
                    return (
                      <Link
                        key={item.href}
                        href={item.href}
                        className={cn(
                          'flex justify-center items-center p-2 rounded-md transition-colors',
                          isActive
                            ? 'bg-sidebar-primary text-sidebar-primary-foreground'
                            : 'text-sidebar-foreground/50 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
                        )}
                        title={item.label}
                      >
                        <SubIcon className="w-3.5 h-3.5" />
                      </Link>
                    )
                  })}
                </div>
              )}
            </div>
          )
        })}
      </nav>

      {/* Usuário */}
      <div className="border-t border-sidebar-border p-3 shrink-0">
        {!collapsed ? (
          <div className="flex items-center gap-2">
            <div className="w-7 h-7 rounded-full bg-primary flex items-center justify-center shrink-0">
              <span className="text-[10px] font-bold text-primary-foreground">
                {user?.name?.slice(0, 2).toUpperCase() ?? 'AD'}
              </span>
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-xs font-semibold text-sidebar-foreground truncate leading-tight">{user?.name}</p>
              <p className="text-[10px] text-sidebar-foreground/50 truncate">
                {getRoleLabel(role)}
              </p>
            </div>
            <button
              onClick={handleLogout}
              className="p-1.5 rounded hover:bg-sidebar-accent transition-colors"
              aria-label="Sair"
              title="Sair"
            >
              <LogOut className="w-3.5 h-3.5 text-sidebar-foreground/50" />
            </button>
          </div>
        ) : (
          <button
            onClick={handleLogout}
            className="w-full flex justify-center p-1.5 rounded hover:bg-sidebar-accent transition-colors"
            aria-label="Sair"
            title="Sair"
          >
            <LogOut className="w-3.5 h-3.5 text-sidebar-foreground/50" />
          </button>
        )}
      </div>
    </aside>
  )
}
