import { createFileRoute } from '@tanstack/react-router'
import { z } from 'zod'
import { AsciiPanel } from '#/components/ascii/AsciiPanel'
import { VersusArena } from '#/components/panels/VersusArena'
import type { MarketItem } from '#/components/panels/MarketGrid'
import { MarketGrid } from '#/components/panels/MarketGrid'
import type { CombatLogEntry } from '#/components/panels/EngagementLog'
import { EngagementLog } from '#/components/panels/EngagementLog'

// Search parameters validator matching AGENTS.md Rule A compliance
const searchSchema = z.object({
  quadrant: z.enum(['alpha', 'beta', 'gamma', 'delta']),
  currency: z.enum(['Latinum', 'Credits']).default('Latinum'),
  marketCategory: z
    .enum(['primary', 'secondary', 'exotic', 'all'])
    .default('all'),
})

export const Route = createFileRoute('/quadrants/$sectorId')({
  validateSearch: searchSchema,
  component: MatchDetailView,
})

function MatchDetailView() {
  const { sectorId } = Route.useParams()
  const { marketCategory } = Route.useSearch()

  // Full detailed mock matches database matching taxonomy.yaml
  const matchesDetails:
    | Record<
        string,
        {
          name: string
          status: 'LIVE' | 'PRE' | 'RES'
          kineticYield: number
          tick: number
          maxTicks: number
          venue: {
            name: string
            coordinates: string
            shieldModifier: number
            damageModifier: number
            evasionModifier: number
            tags: string[]
          }
          homeFaction: {
            name: string
            abbreviation: string
            glyph: string
            colorCode: string
            shieldCapacity: number
            attack: number
            evasion: number
            activeEffects: Array<{
              name: string
              description: string
              remainingTicks: number
            }>
          }
          awayFaction: {
            name: string
            abbreviation: string
            glyph: string
            colorCode: string
            shieldCapacity: number
            attack: number
            evasion: number
            activeEffects: Array<{
              name: string
              description: string
              remainingTicks: number
            }>
          }
          markets: MarketItem[]
          logs: CombatLogEntry[]
        }
      >
    | undefined = {
    'sector-001': {
      name: 'Sector 001 — Sol Array',
      status: 'LIVE',
      kineticYield: 14.7,
      tick: 42,
      maxTicks: 90,
      venue: {
        name: 'Sol System Orbit',
        coordinates: '001-ALPHA-0',
        shieldModifier: 1.0,
        damageModifier: 1.0,
        evasionModifier: 1.0,
        tags: ['orbital-grid', 'starfleet-array'],
      },
      homeFaction: {
        name: 'Starfleet Command',
        abbreviation: 'SFC',
        glyph: '◆',
        colorCode: '#34d399',
        shieldCapacity: 62,
        attack: 75,
        evasion: 55,
        activeEffects: [],
      },
      awayFaction: {
        name: 'Borg Collective',
        abbreviation: 'BRG',
        glyph: '█',
        colorCode: '#38bdf8',
        shieldCapacity: 71,
        attack: 90,
        evasion: 15,
        activeEffects: [
          {
            name: 'BORG ADAPTATION',
            description: 'Incoming damage multiplier ×0.5',
            remainingTicks: 3,
          },
        ],
      },
      markets: [
        {
          id: 's1-m1',
          templateId: 'moneyline',
          name: 'COMBAT RESOLUTION — MONEYLINE',
          category: 'primary',
          selections: [
            {
              id: 's1-m1-o1',
              name: 'Starfleet Victory',
              price: 2.85,
              factionGlyph: '◆',
            },
            {
              id: 's1-m1-o2',
              name: 'Borg Assimilation',
              price: 1.48,
              factionGlyph: '█',
            },
          ],
        },
        {
          id: 's1-m2',
          templateId: 'first-breach',
          name: 'FIRST SHIELD BREACH',
          category: 'primary',
          selections: [
            {
              id: 's1-m2-o1',
              name: 'SFC Shields First',
              price: 1.65,
              factionGlyph: '◆',
            },
            {
              id: 's1-m2-o2',
              name: 'BRG Shields First',
              price: 2.2,
              factionGlyph: '█',
            },
          ],
        },
        {
          id: 's1-m3',
          templateId: 'kinetic-yield',
          name: 'TOTAL KINETIC YIELD',
          category: 'secondary',
          selections: [
            {
              id: 's1-m3-o1',
              name: 'Over 18.5 TW',
              price: 1.85,
              factionGlyph: '◇',
            },
            {
              id: 's1-m3-o2',
              name: 'Under 18.5 TW',
              price: 1.85,
              factionGlyph: '◇',
            },
          ],
        },
      ],
      logs: [
        {
          id: 'l1',
          tick: 42,
          message: '◆ Starfleet Command fires — HIT — 4.2% shield damage',
          type: 'combat',
        },
        {
          id: 'l2',
          tick: 42,
          message: '█ Borg Collective fires — MISS — Evasion successful',
          type: 'combat',
        },
        {
          id: 'l3',
          tick: 38,
          message:
            '⚡ EVENT: Borg Adaptation active — Incoming damage multiplier ×0.5',
          type: 'event',
        },
      ],
    },
    'bajor-wormhole': {
      name: 'Bajor Sector — DS9',
      status: 'LIVE',
      kineticYield: 8.2,
      tick: 31,
      maxTicks: 75,
      venue: {
        name: 'Denorios Belt — Wormhole',
        coordinates: 'BAJ-WORM-1',
        shieldModifier: 0.85,
        damageModifier: 1.15,
        evasionModifier: 0.9,
        tags: ['high-gravitational', 'plasma-clouds'],
      },
      homeFaction: {
        name: 'Bajoran Militia',
        abbreviation: 'BAJ',
        glyph: '☼',
        colorCode: '#fb923c',
        shieldCapacity: 48,
        attack: 60,
        evasion: 75,
        activeEffects: [],
      },
      awayFaction: {
        name: 'The Dominion',
        abbreviation: 'DOM',
        glyph: '◉',
        colorCode: '#fb7185',
        shieldCapacity: 55,
        attack: 85,
        evasion: 40,
        activeEffects: [],
      },
      markets: [
        {
          id: 's2-m1',
          templateId: 'moneyline',
          name: 'COMBAT RESOLUTION — MONEYLINE',
          category: 'primary',
          selections: [
            {
              id: 's2-m1-o1',
              name: 'Bajoran Defiance',
              price: 2.1,
              factionGlyph: '☼',
            },
            {
              id: 's2-m1-o2',
              name: 'Dominion Conquest',
              price: 1.72,
              factionGlyph: '◉',
            },
          ],
        },
      ],
      logs: [
        {
          id: 'l2-1',
          tick: 31,
          message: '☼ Bajoran Militia fires — HIT — 3.1% shield damage',
          type: 'combat',
        },
        {
          id: 'l2-2',
          tick: 30,
          message: '◉ The Dominion fires — HIT — 5.4% shield damage',
          type: 'combat',
        },
      ],
    },
    'wolf-359': {
      name: 'Wolf 359 Outpost',
      status: 'PRE',
      kineticYield: 0.0,
      tick: 0,
      maxTicks: 90,
      venue: {
        name: 'Wolf 359 Debris Field',
        coordinates: '359-DEBRIS-2',
        shieldModifier: 0.95,
        damageModifier: 1.1,
        evasionModifier: 0.8,
        tags: ['debris-field', 'high-anomaly'],
      },
      homeFaction: {
        name: 'Starfleet Command',
        abbreviation: 'SFC',
        glyph: '◆',
        colorCode: '#34d399',
        shieldCapacity: 100,
        attack: 75,
        evasion: 55,
        activeEffects: [],
      },
      awayFaction: {
        name: 'Borg Collective',
        abbreviation: 'BRG',
        glyph: '█',
        colorCode: '#38bdf8',
        shieldCapacity: 100,
        attack: 90,
        evasion: 15,
        activeEffects: [],
      },
      markets: [
        {
          id: 's3-m1',
          templateId: 'moneyline',
          name: 'COMBAT RESOLUTION — MONEYLINE',
          category: 'primary',
          selections: [
            {
              id: 's3-m1-o1',
              name: 'Starfleet Victory',
              price: 2.4,
              factionGlyph: '◆',
            },
            {
              id: 's3-m1-o2',
              name: 'Borg Assimilation',
              price: 1.62,
              factionGlyph: '█',
            },
          ],
        },
      ],
      logs: [
        {
          id: 'l3-1',
          tick: 0,
          message:
            'Subspace communications linked. Awaiting combat deployment.',
          type: 'system',
        },
      ],
    },
  }

  // Get current match detail
  const match = (matchesDetails as Record<string, any>)[sectorId]

  if (!match) {
    return (
      <AsciiPanel
        title="Engagement Matrix"
        subtitle="Telemetry Lost"
        variant="amber"
      >
        <div className="p-8 text-center font-mono text-xs text-rose-500 italic space-y-4">
          <div>&gt; ERROR: SECTOR ARRAY COORDINATES OFFLINE</div>
          <div className="text-slate-400">
            Link signals for sector [{sectorId}] cannot be parsed. Select an
            active fleet connection link from the left array.
          </div>
        </div>
      </AsciiPanel>
    )
  }

  return (
    <AsciiPanel
      title="Engagement Matrix"
      subtitle={match.name}
      variant="emerald"
    >
      <div className="space-y-4 font-mono select-none h-full flex flex-col justify-between">
        {/* Versus Arena header and stats */}
        <VersusArena
          home={match.homeFaction}
          away={match.awayFaction}
          kineticYield={match.kineticYield}
          tick={match.tick}
          maxTicks={match.maxTicks}
          venue={match.venue}
        />

        {/* Markets configuration grid */}
        <div>
          <div className="text-emerald-400 font-bold text-xs uppercase tracking-wider mb-2">
            &gt; AVAILABLE ODDS MATRICES
          </div>
          <MarketGrid
            matchId={sectorId}
            matchName={match.name}
            markets={match.markets}
            currentCategory={marketCategory}
          />
        </div>

        {/* Live log feed specific to match */}
        <div>
          <div className="text-slate-600 text-[10px] font-bold tracking-wider mb-1.5 px-0.5">
            &gt; TACTICAL ENGAGEMENT LOG
          </div>
          <EngagementLog logs={match.logs} />
        </div>
      </div>
    </AsciiPanel>
  )
}
