import { useState } from 'react'
import { Link } from '@tanstack/react-router'
import { ShieldBar } from '#/components/ascii/ShieldBar'
import { StatusBadge } from '#/components/ascii/StatusBadge'
import { GlyphIcon } from '#/components/ascii/GlyphIcon'

// ─── TYPES ──────────────────────────────────────────────────────────────

interface ActiveMatchSummary {
  id: string
  name: string
  quadrant: 'alpha' | 'beta' | 'gamma' | 'delta'
  status: 'LIVE' | 'PRE' | 'RES'
  homeFaction: {
    abbreviation: string
    glyph: string
    colorCode: string
    shieldCapacity: number
  }
  awayFaction: {
    abbreviation: string
    glyph: string
    colorCode: string
    shieldCapacity: number
  }
}

interface QuadrantConfig {
  id: string
  name: string
  glyph: string
}

// ─── MAIN COMPONENT ─────────────────────────────────────────────────────

export function NavigationMenu() {
  // Collapsible quadrant groups state
  const [openQuadrants, setOpenQuadrants] = useState<Record<string, boolean>>({
    alpha: true,
    beta: true,
    gamma: false,
    delta: false,
  })

  const toggleQuadrant = (q: string) => {
    setOpenQuadrants((prev) => ({
      ...prev,
      [q]: !prev[q],
    }))
  }

  // Mock Active Matches aligned with taxonomy.yaml and color codes
  const matches: ActiveMatchSummary[] = [
    {
      id: 'sector-001',
      name: 'Sector 001 — Sol Array',
      quadrant: 'alpha',
      status: 'LIVE',
      homeFaction: {
        abbreviation: 'SFC',
        glyph: '◆',
        colorCode: '#34d399',
        shieldCapacity: 62,
      },
      awayFaction: {
        abbreviation: 'BRG',
        glyph: '█',
        colorCode: '#38bdf8',
        shieldCapacity: 71,
      },
    },
    {
      id: 'bajor-wormhole',
      name: 'Bajor Sector — DS9',
      quadrant: 'alpha',
      status: 'LIVE',
      homeFaction: {
        abbreviation: 'BAJ',
        glyph: '☼',
        colorCode: '#fb923c',
        shieldCapacity: 48,
      },
      awayFaction: {
        abbreviation: 'DOM',
        glyph: '◉',
        colorCode: '#fb7185',
        shieldCapacity: 55,
      },
    },
    {
      id: 'wolf-359',
      name: 'Wolf 359 Outpost',
      quadrant: 'alpha',
      status: 'PRE',
      homeFaction: {
        abbreviation: 'SFC',
        glyph: '◆',
        colorCode: '#34d399',
        shieldCapacity: 100,
      },
      awayFaction: {
        abbreviation: 'BRG',
        glyph: '█',
        colorCode: '#38bdf8',
        shieldCapacity: 100,
      },
    },
    {
      id: 'qonos-arena',
      name: "Qo'noS Sector — Warrior's Ring",
      quadrant: 'beta',
      status: 'LIVE',
      homeFaction: {
        abbreviation: 'KLG',
        glyph: '⚔',
        colorCode: '#f87171',
        shieldCapacity: 88,
      },
      awayFaction: {
        abbreviation: 'ROM',
        glyph: '◈',
        colorCode: '#a78bfa',
        shieldCapacity: 72,
      },
    },
    {
      id: 'neutral-zone',
      name: 'The Neutral Zone',
      quadrant: 'beta',
      status: 'LIVE',
      homeFaction: {
        abbreviation: 'ROM',
        glyph: '◈',
        colorCode: '#a78bfa',
        shieldCapacity: 90,
      },
      awayFaction: {
        abbreviation: 'SFC',
        glyph: '◆',
        colorCode: '#34d399',
        shieldCapacity: 95,
      },
    },
    {
      id: 'karemma-trade-corridor',
      name: 'Karemma Trade Corridor',
      quadrant: 'gamma',
      status: 'LIVE',
      homeFaction: {
        abbreviation: 'KRM',
        glyph: '◊',
        colorCode: '#fcd34d',
        shieldCapacity: 65,
      },
      awayFaction: {
        abbreviation: 'DOS',
        glyph: '▬',
        colorCode: '#c084fc',
        shieldCapacity: 80,
      },
    },
    {
      id: 'grid-325',
      name: 'Grid 325 — Borg Corridor',
      quadrant: 'delta',
      status: 'LIVE',
      homeFaction: {
        abbreviation: 'BRG',
        glyph: '█',
        colorCode: '#38bdf8',
        shieldCapacity: 15,
      },
      awayFaction: {
        abbreviation: 'S84',
        glyph: '∞',
        colorCode: '#ec4899',
        shieldCapacity: 99,
      },
    },
    {
      id: 'hirogen-relay',
      name: 'Hirogen Relay Nexus',
      quadrant: 'delta',
      status: 'LIVE',
      homeFaction: {
        abbreviation: 'HRG',
        glyph: '⊗',
        colorCode: '#fbbf24',
        shieldCapacity: 75,
      },
      awayFaction: {
        abbreviation: 'KZN',
        glyph: '╳',
        colorCode: '#f97316',
        shieldCapacity: 40,
      },
    },
  ]

  const quadrants: QuadrantConfig[] = [
    { id: 'alpha', name: 'ALPHA QUADRANT', glyph: 'α' },
    { id: 'beta', name: 'BETA QUADRANT', glyph: 'β' },
    { id: 'gamma', name: 'GAMMA QUADRANT', glyph: 'γ' },
    { id: 'delta', name: 'DELTA QUADRANT', glyph: 'δ' },
  ]

  return (
    <div className="space-y-4 font-mono select-none">
      {/* 00 Grid Overview Dashboard */}
      <div>
        <Link
          to="/"
          className="group w-full flex justify-between items-center p-2 border border-slate-900 bg-slate-950/40 text-slate-400 hover:border-amber-500/40 hover:bg-slate-900/40 transition-all text-xs"
          activeProps={{
            className:
              '!border-emerald-500/50 !text-emerald-400 !bg-emerald-950/20',
          }}
          activeOptions={{ exact: true }}
        >
          <span className="font-bold tracking-wider group-hover:translate-x-1 transition-transform">
            &gt; GRID OVERVIEW
          </span>
          <span className="opacity-60">[00]</span>
        </Link>
      </div>

      <div className="border-t border-slate-900 pt-2">
        <div className="text-slate-600 text-[10px] font-bold tracking-widest mb-2 px-1">
          &gt; LIVE ENGAGEMENTS
        </div>

        <div className="space-y-1.5">
          {quadrants.map((quad) => (
            <QuadrantGroup
              key={quad.id}
              quadrant={quad}
              isOpen={openQuadrants[quad.id]}
              onToggle={() => toggleQuadrant(quad.id)}
              matches={matches.filter((m) => m.quadrant === quad.id)}
            />
          ))}
        </div>
      </div>

      {/* Archives Section */}
      <div className="border-t border-slate-900 pt-2">
        <div className="text-slate-600 text-[10px] font-bold tracking-widest mb-2 px-1">
          &gt; STATION ARCHIVES
        </div>
        <div className="flex flex-col gap-1">
          <ArchiveLink to="/ledger" label="Wager Ledger" num="01" glyph="▤" />
          <ArchiveLink
            to="/registry/factions"
            label="Faction Registry"
            num="02"
            glyph="◆"
          />
          <ArchiveLink
            to="/registry/venues"
            label="Venue Database"
            num="03"
            glyph="◇"
          />
          <ArchiveLink
            to="/schedule"
            label="Transmission Schedule"
            num="04"
            glyph="☼"
          />
        </div>
      </div>
    </div>
  )
}

// ─── SUB-COMPONENTS ─────────────────────────────────────────────────────

interface QuadrantGroupProps {
  quadrant: QuadrantConfig
  isOpen: boolean
  onToggle: () => void
  matches: ActiveMatchSummary[]
}

function QuadrantGroup({
  quadrant,
  isOpen,
  onToggle,
  matches,
}: QuadrantGroupProps) {
  return (
    <div className="border border-slate-900/60 bg-black/20">
      <button
        onClick={onToggle}
        className="w-full text-left p-2 bg-slate-950/20 hover:bg-slate-900/20 flex justify-between items-center text-xs font-bold text-slate-400 cursor-pointer border-none"
      >
        <span className="flex items-center gap-1.5">
          <span className="text-[10px] text-slate-600">
            {isOpen ? '▼' : '▸'}
          </span>
          {quadrant.name}
        </span>
        <span className="text-[10px] text-slate-500 bg-slate-900/60 px-1 border border-slate-800">
          [{quadrant.glyph}]
        </span>
      </button>

      {isOpen && (
        <div className="border-t border-slate-950/80 p-1 flex flex-col gap-1">
          {matches.length === 0 ? (
            <div className="p-2 text-[10px] text-slate-600 italic">
              No active engagements
            </div>
          ) : (
            matches.map((match) => (
              <MatchNavItem key={match.id} match={match} />
            ))
          )}
        </div>
      )}
    </div>
  )
}

interface MatchNavItemProps {
  match: ActiveMatchSummary
}

function MatchNavItem({ match }: MatchNavItemProps) {
  return (
    <Link
      to="/quadrants/$sectorId"
      params={{ sectorId: match.id }}
      search={{ quadrant: match.quadrant, currency: 'Latinum' }}
      className="group p-1.5 bg-black border border-slate-950 hover:border-amber-500/30 text-slate-400 flex flex-col gap-1 transition-all"
      activeProps={{
        className:
          '!border-emerald-500/50 !text-emerald-400 !bg-emerald-950/20',
      }}
    >
      <div className="flex justify-between items-center text-[10px]">
        <span className="truncate group-hover:translate-x-0.5 transition-transform flex items-center gap-1">
          <GlyphIcon
            glyph={match.homeFaction.glyph}
            colorCode={match.homeFaction.colorCode}
          />
          <span className="font-bold">{match.homeFaction.abbreviation}</span>
          <span className="text-slate-600 text-[8px]">VS</span>
          <GlyphIcon
            glyph={match.awayFaction.glyph}
            colorCode={match.awayFaction.colorCode}
          />
          <span className="font-bold">{match.awayFaction.abbreviation}</span>
        </span>

        <StatusBadge status={match.status} />
      </div>

      {match.status === 'LIVE' && (
        <ShieldBar
          homeShield={match.homeFaction.shieldCapacity}
          awayShield={match.awayFaction.shieldCapacity}
        />
      )}
    </Link>
  )
}

interface ArchiveLinkProps {
  to: string
  label: string
  num: string
  glyph: string
}

function ArchiveLink({ to, label, num, glyph }: ArchiveLinkProps) {
  return (
    <Link
      to={to}
      className="w-full text-left p-2 border border-slate-900 text-slate-500 hover:text-slate-300 transition-all text-xs flex justify-between"
      activeProps={{
        className:
          '!text-emerald-400 !border-emerald-500/30 !bg-emerald-950/10',
      }}
    >
      <span>
        [{num}] {label}
      </span>
      <span className="opacity-40">{glyph}</span>
    </Link>
  )
}
