'use client'

import { useState } from 'react'

import { useI18n } from '@/components/providers/i18n-provider'
import { Button, Notice } from '@/components/ui/controls'
import { Badge, Panel, PanelBody, PanelHeader, StatCard } from '@/components/ui/display'
import { api, ApiClientError } from '@/lib/api/client'
import { cn } from '@/lib/cn'

type ScenarioKey = 'extreme_heat' | 'transformer_failure' | 'demand_spike'

interface AgentSummary {
  key: string
  status: string
  summary: string
  summaryAr: string
  confidence: number
}

interface RunResult {
  assetCode: string
  agents: AgentSummary[]
  orchestration: {
    unifiedRisk: number
    band: string
    rationale: string
    rationaleAr: string
    preventionWindow: { etaMinutes: number | null; safeWindowMin: number }
    confidence: { overall: number }
    recommended: { label: string; labelAr: string; riskBefore: number; riskAfter: number } | null
  }
}

/**
 * Judge Mode (§47).
 *
 * Three buttons, each a real scenario overlay sent to the same orchestrator endpoint the
 * console uses. Nothing is pre-baked: the numbers that come back are computed when the
 * button is pressed, which is the only version of "try it yourself" worth offering.
 */
const SCENARIOS: Record<ScenarioKey, { overlay: Record<string, number | string | null>; asset?: string }> = {
  extreme_heat: { overlay: { tempDeltaC: 7, loadDeltaPct: 14, regionCode: 'RYD' } },
  transformer_failure: { overlay: { loadDeltaPct: 26, regionCode: 'RYD' }, asset: 'T-108' },
  demand_spike: { overlay: { loadDeltaPct: 22, regionCode: 'RYD' } },
}

export function JudgeMode({ defaultAsset }: { defaultAsset: string }) {
  const { t, locale, n } = useI18n()
  const ar = locale === 'ar'

  const [active, setActive] = useState<ScenarioKey | null>(null)
  const [result, setResult] = useState<RunResult | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)

  const run = async (key: ScenarioKey) => {
    setBusy(true)
    setActive(key)
    setError(null)
    try {
      const scenario = SCENARIOS[key]
      setResult(
        await api.post<RunResult>('/api/agents/run', {
          assetCode: scenario.asset ?? defaultAsset,
          overlay: scenario.overlay,
        }),
      )
    } catch (cause) {
      setError(cause instanceof ApiClientError ? (ar ? cause.failure.messageAr : cause.failure.message) : String(cause))
    } finally {
      setBusy(false)
    }
  }

  return (
    <Panel glow>
      <PanelHeader
        title={t('hackathon.judgeMode')}
        subtitle={t('hackathon.judgeHint')}
        action={<Badge tone="accent">{t('common.simulated')}</Badge>}
      />
      <PanelBody className="space-y-4 pt-0">
        <div className="flex flex-wrap gap-2">
          {(Object.keys(SCENARIOS) as ScenarioKey[]).map((key) => (
            <Button
              key={key}
              variant={active === key ? 'primary' : 'secondary'}
              onClick={() => run(key)}
              loading={busy && active === key}
            >
              {t(`hackathon.scenario.${key}`)}
            </Button>
          ))}
        </div>

        {error ? <Notice tone="danger">{error}</Notice> : null}
        {busy ? <p className="text-xs text-text-muted">{t('hackathon.running')}</p> : null}

        {result ? (
          <div className="space-y-4">
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
              <StatCard
                label={t('aiOps.unifiedRisk')}
                value={n(result.orchestration.unifiedRisk, { maximumFractionDigits: 0 })}
                unit="%"
                state={
                  result.orchestration.unifiedRisk >= 70
                    ? 'critical'
                    : result.orchestration.unifiedRisk >= 45
                      ? 'warning'
                      : 'normal'
                }
                hint={result.assetCode}
              />
              <StatCard
                label={t('preventionWindow.eventIn')}
                value={
                  result.orchestration.preventionWindow.etaMinutes === null
                    ? '—'
                    : n(result.orchestration.preventionWindow.etaMinutes)
                }
                unit={t('common.minutes')}
              />
              <StatCard
                label={t('preventionWindow.safeWindow')}
                value={n(result.orchestration.preventionWindow.safeWindowMin)}
                unit={t('common.minutes')}
              />
              <StatCard
                label={t('confidence.overall')}
                value={n(result.orchestration.confidence.overall, { maximumFractionDigits: 0 })}
                unit="%"
              />
            </div>

            {result.orchestration.recommended ? (
              <div className="rounded-lg border border-brand/40 bg-brand/6 p-3">
                <p className="text-[10px] uppercase tracking-wide text-text-faint">
                  {t('selfHealing.recommended')}
                </p>
                <p className="mt-1 text-sm font-medium text-text">
                  {ar
                    ? result.orchestration.recommended.labelAr
                    : result.orchestration.recommended.label}
                </p>
                <p className="tnum mt-1 text-xs text-text-muted">
                  <span className="text-critical">
                    {n(result.orchestration.recommended.riskBefore, { maximumFractionDigits: 0 })}%
                  </span>
                  {' → '}
                  <span className="text-normal">
                    {n(result.orchestration.recommended.riskAfter, { maximumFractionDigits: 0 })}%
                  </span>
                </p>
              </div>
            ) : null}

            <p className="text-xs leading-relaxed text-text-muted">
              {ar ? result.orchestration.rationaleAr : result.orchestration.rationale}
            </p>

            <ul className="grid gap-2 sm:grid-cols-2">
              {result.agents.map((agent) => (
                <li
                  key={agent.key}
                  className={cn(
                    'rounded-lg border border-border bg-surface-2/40 p-2.5',
                    agent.status === 'alarming' && 'border-critical/35',
                  )}
                >
                  <p className="text-[11px] font-medium text-text">{t(`agents.key.${agent.key}`)}</p>
                  <p className="mt-0.5 text-[10px] leading-relaxed text-text-muted">
                    {ar ? agent.summaryAr : agent.summary}
                  </p>
                </li>
              ))}
            </ul>
          </div>
        ) : null}
      </PanelBody>
    </Panel>
  )
}
