'use client'

import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { useState } from 'react'

import { useI18n } from '@/components/providers/i18n-provider'
import { Wordmark } from '@/components/brand/logo'
import {
  IconAlert,
  IconAsset,
  IconAudit,
  IconClock,
  IconClose,
  IconCommand,
  IconCopilot,
  IconDemo,
  IconDna,
  IconExecutive,
  IconForecast,
  IconGrid,
  IconIncident,
  IconIntegration,
  IconMaintenance,
  IconMap,
  IconMenu,
  IconModel,
  IconPrediction,
  IconRenewable,
  IconRoles,
  IconScenario,
  IconScreen,
  IconSettings,
  IconSimulation,
  IconUsers,
  IconAgents,
  IconWarRoom,
  IconCascade,
  IconCounterfactual,
  IconSelfHealing,
  IconRadar,
  IconTwin,
  IconKnowledge,
  IconDecisions,
  IconHackathon,
  IconResilience,
  IconTrust,
  IconReports,
} from '@/components/ui/icons'
import { cn } from '@/lib/cn'
import type { NavGroup, NavItem } from '@/lib/navigation'

const ICONS: Record<string, (p: { className?: string }) => React.ReactElement> = {
  command: IconCommand,
  executive: IconExecutive,
  grid: IconGrid,
  map: IconMap,
  alert: IconAlert,
  incident: IconIncident,
  prediction: IconPrediction,
  dna: IconDna,
  clock: IconClock,
  scenario: IconScenario,
  simulation: IconSimulation,
  forecast: IconForecast,
  renewable: IconRenewable,
  copilot: IconCopilot,
  asset: IconAsset,
  maintenance: IconMaintenance,
  model: IconModel,
  integration: IconIntegration,
  audit: IconAudit,
  settings: IconSettings,
  users: IconUsers,
  roles: IconRoles,
  demo: IconDemo,
  screen: IconScreen,
  agents: IconAgents,
  warroom: IconWarRoom,
  cascade: IconCascade,
  counterfactual: IconCounterfactual,
  selfhealing: IconSelfHealing,
  radar: IconRadar,
  twin: IconTwin,
  knowledge: IconKnowledge,
  decisions: IconDecisions,
  hackathon: IconHackathon,
  resilience: IconResilience,
  trust: IconTrust,
  reports: IconReports,
}

function NavLink({ item, onNavigate }: { item: NavItem; onNavigate?: () => void }) {
  const { t } = useI18n()
  const pathname = usePathname()
  const Icon = ICONS[item.icon] ?? IconGrid
  // `/assets` must stay highlighted while the user is on `/assets/T-108`.
  const active = pathname === item.href || pathname.startsWith(`${item.href}/`)

  return (
    <Link
      href={item.href}
      onClick={onNavigate}
      aria-current={active ? 'page' : undefined}
      className={cn(
        'group relative flex items-center gap-2.5 rounded-lg px-2.5 py-2 text-[13px] font-medium transition-colors',
        active
          ? 'bg-brand/12 text-brand'
          : 'text-text-muted hover:bg-surface-2 hover:text-text',
      )}
    >
      {active ? (
        <span className="absolute inset-y-1.5 start-0 w-0.5 rounded-full bg-brand" aria-hidden />
      ) : null}
      <Icon className={cn('size-4', active ? 'text-brand' : 'text-text-faint group-hover:text-text-muted')} />
      <span className="truncate">{t(`nav.${item.key}`)}</span>
    </Link>
  )
}

function NavContent({
  groups,
  specials,
  onNavigate,
}: {
  groups: NavGroup[]
  specials: NavItem[]
  onNavigate?: () => void
}) {
  const { t } = useI18n()
  return (
    <nav aria-label={t('a11y.mainNavigation')} className="flex-1 space-y-6 overflow-y-auto px-3 py-4">
      {specials.length > 0 ? (
        <div className="space-y-1">
          {specials.map((item) => (
            <NavLink key={item.href} item={item} onNavigate={onNavigate} />
          ))}
        </div>
      ) : null}

      {groups.map((group) => (
        <div key={group.key}>
          <p className="mb-1.5 px-2.5 text-[10px] font-semibold uppercase tracking-[0.14em] text-text-faint">
            {t(`nav.groups.${group.key}`)}
          </p>
          <div className="space-y-0.5">
            {group.items.map((item) => (
              <NavLink key={item.href} item={item} onNavigate={onNavigate} />
            ))}
          </div>
        </div>
      ))}
    </nav>
  )
}

/** The persistent desktop rail. */
export function Sidebar({
  groups,
  specials,
  footer,
}: {
  groups: NavGroup[]
  specials: NavItem[]
  footer: React.ReactNode
}) {
  const { locale } = useI18n()

  return (
    <aside className="hidden w-60 shrink-0 flex-col border-e border-border bg-surface/40 lg:flex">
      <div className="flex h-14 items-center border-b border-border px-4">
        <Link href="/command-center">
          <Wordmark locale={locale} />
        </Link>
      </div>
      <NavContent groups={groups} specials={specials} />
      <div className="border-t border-border p-3">{footer}</div>
    </aside>
  )
}

/**
 * The small-screen equivalent: a trigger in the top bar and a drawer. Kept separate from
 * the rail so the shell can place each where it belongs without rendering the navigation
 * twice into the layout.
 */
export function MobileNav({
  groups,
  specials,
  footer,
}: {
  groups: NavGroup[]
  specials: NavItem[]
  footer: React.ReactNode
}) {
  const { t, locale } = useI18n()
  const [open, setOpen] = useState(false)

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        aria-label={t('a11y.toggleSidebar')}
        aria-expanded={open}
        className="rounded-lg border border-border bg-surface-2 p-2 text-text-muted transition-colors hover:text-text lg:hidden"
      >
        <IconMenu className="size-4" />
      </button>

      {open ? (
        <div className="fixed inset-0 z-50 lg:hidden">
          <div
            className="absolute inset-0 bg-black/70 backdrop-blur-sm"
            onClick={() => setOpen(false)}
            aria-hidden
          />
          <aside className="absolute inset-y-0 start-0 flex w-72 flex-col border-e border-border bg-surface shadow-2xl">
            <div className="flex h-14 items-center justify-between border-b border-border px-4">
              <Wordmark locale={locale} />
              <button
                type="button"
                onClick={() => setOpen(false)}
                aria-label={t('common.close')}
                className="rounded-md p-1 text-text-faint hover:text-text"
              >
                <IconClose className="size-4" />
              </button>
            </div>
            <NavContent groups={groups} specials={specials} onNavigate={() => setOpen(false)} />
            <div className="border-t border-border p-3">{footer}</div>
          </aside>
        </div>
      ) : null}
    </>
  )
}
