'use client'

import { useState } from 'react'

import { Button, Notice, Select } from '@/components/ui/controls'
import { Badge, Panel, PanelBody, PanelHeader, StatCard } from '@/components/ui/display'
import { useI18n } from '@/components/providers/i18n-provider'
import { api } from '@/lib/api/client'
import { formatNumber } from '@/lib/i18n/translate'
import { cn } from '@/lib/cn'

/**
 * Red team versus blue team (§24, §25, §26).
 *
 * The three resilience readings are shown together — before, during, after — because the
 * recovery figure only means something as a difference. A page that showed "resilience
 * 69" after a response, without the 66 it started from, would be reporting a number
 * rather than an outcome.
 *
 * The resources the scenario removes are listed under the stress, so it is obvious why a
 * response is missing rather than looking like an oversight.
 */

export interface StressScenarioView {
  kind: string
  title: string
  titleAr: string
  description: string
  descriptionAr: string
  observabilityLossPct: number
  removes: string[]
}

export interface RedBlueResultView {
  code: string | null
  assetCode: string
  resilienceBefore: number
  resilienceDuring: number
  riskBefore: number
  riskDuring: number
  recovered: number
  narrative: string
  narrativeAr: string
  observabilityLossPct: number
  removedResources: string[]
  stress: { kind: string; title: string; titleAr: string }
  ranked: Array<{
    rank: number
    isRecommended: boolean
    resilienceAfter: number
    riskAfter: number
    recoveryMin: number
    costIndex: number
    customersImpacted: number
    candidate: { key: string; label: string; labelAr: string }
  }>
}

export function RedBlueLab({
  scenarios,
  regions,
  canRun,
}: {
  scenarios: StressScenarioView[]
  regions: Array<{ code: string; name: string; nameAr: string }>
  canRun: boolean
}) {
  const { t, locale } = useI18n()
  const [stressKind, setStressKind] = useState(scenarios[0]?.kind ?? 'combined')
  const [regionCode, setRegionCode] = useState('')
  const [result, setResult] = useState<RedBlueResultView | null>(null)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const num = (value: number, digits = 0) =>
    formatNumber(locale, value, { maximumFractionDigits: digits })

  const selected = scenarios.find((scenario) => scenario.kind === stressKind)

  const run = async () => {
    setBusy(true)
    setError(null)
    try {
      setResult(
        await api.post<RedBlueResultView>('/api/resilience/red-blue', {
          stressKind,
          regionCode: regionCode || null,
          persist: true,
        }),
      )
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : t('common.error'))
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="space-y-4">
      <Panel>
        <PanelHeader title={t('redBlue.title')} subtitle={t('redBlue.subtitle')} />
        <PanelBody className="space-y-3">
          <div className="flex flex-wrap items-end gap-3">
            <label className="min-w-0 flex-1 basis-56">
              <span className="mb-1 block text-[11px] text-text-muted">{t('redBlue.stress')}</span>
              <Select value={stressKind} onChange={(event) => setStressKind(event.target.value)}>
                {scenarios.map((scenario) => (
                  <option key={scenario.kind} value={scenario.kind}>
                    {locale === 'ar' ? scenario.titleAr : scenario.title}
                  </option>
                ))}
              </Select>
            </label>
            <label className="min-w-0 basis-44">
              <span className="mb-1 block text-[11px] text-text-muted">{t('discovery.scope')}</span>
              <Select value={regionCode} onChange={(event) => setRegionCode(event.target.value)}>
                <option value="">{t('discovery.national')}</option>
                {regions.map((region) => (
                  <option key={region.code} value={region.code}>
                    {locale === 'ar' ? region.nameAr : region.name}
                  </option>
                ))}
              </Select>
            </label>
            {canRun ? (
              <Button onClick={run} disabled={busy}>
                {busy ? t('common.running') : t('redBlue.run')}
              </Button>
            ) : null}
          </div>

          {selected ? (
            <div className="rounded-lg border border-critical/25 bg-critical/6 px-3 py-2">
              <div className="flex flex-wrap items-center gap-2">
                <Badge tone="accent" dot>
                  {t('redBlue.redTeam')}
                </Badge>
                <span className="text-[12px] font-medium">
                  {locale === 'ar' ? selected.titleAr : selected.title}
                </span>
              </div>
              <p className="mt-1 text-[11px] leading-relaxed text-text-muted">
                {locale === 'ar' ? selected.descriptionAr : selected.description}
              </p>
              {selected.removes.length || selected.observabilityLossPct > 0 ? (
                <p className="mt-1 text-[10px] text-text-faint">
                  {selected.removes.length ? (
                    <>
                      {t('redBlue.removed')}: {selected.removes.join('، ')}
                    </>
                  ) : null}
                  {selected.observabilityLossPct > 0 ? (
                    <>
                      {selected.removes.length ? ' · ' : ''}
                      {t('redBlue.observability')}: {num(selected.observabilityLossPct)}%
                    </>
                  ) : null}
                </p>
              ) : null}
            </div>
          ) : null}

          {error ? <Notice tone="danger">{error}</Notice> : null}
        </PanelBody>
      </Panel>

      {result ? (
        <>
          <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
            <StatCard label={t('redBlue.before')} value={num(result.resilienceBefore, 1)} />
            <StatCard
              label={t('redBlue.during')}
              value={num(result.resilienceDuring, 1)}
              state="warning"
            />
            <StatCard
              label={t('redBlue.after')}
              value={result.ranked[0] ? num(result.ranked[0].resilienceAfter, 1) : '—'}
              state="normal"
            />
            <StatCard
              label={t('redBlue.recovered')}
              value={`${result.recovered >= 0 ? '+' : ''}${num(result.recovered, 1)}`}
            />
          </div>

          <Panel>
            <PanelHeader
              title={t('redBlue.blueTeam')}
              action={<Badge tone="muted">{t('common.simulated')}</Badge>}
            />
            <PanelBody className="space-y-3">
              <p className="text-[12px] leading-relaxed">
                {locale === 'ar' ? result.narrativeAr : result.narrative}
              </p>

              {result.ranked.length === 0 ? (
                <Notice tone="warning">{t('redBlue.noResponse')}</Notice>
              ) : (
                <ul className="space-y-2">
                  {result.ranked.map((response) => (
                    <li
                      key={response.candidate.key}
                      className={cn(
                        'min-w-0 rounded-lg border px-3 py-2.5',
                        response.isRecommended
                          ? 'border-brand/45 bg-brand/8'
                          : 'border-border bg-surface-2/40',
                      )}
                    >
                      <div className="flex flex-wrap items-baseline gap-2">
                        <span className="text-[12px] font-medium">
                          {locale === 'ar'
                            ? response.candidate.labelAr
                            : response.candidate.label}
                        </span>
                        {response.isRecommended ? (
                          <Badge tone="brand" dot>
                            {t('redBlue.recommended')}
                          </Badge>
                        ) : null}
                      </div>

                      <div className="mt-1.5 grid grid-cols-2 gap-2 sm:grid-cols-4">
                        {(
                          [
                            ['redBlue.after', num(response.resilienceAfter, 1)],
                            ['common.risk', `${num(response.riskAfter)}%`],
                            ['redBlue.recovery', `${response.recoveryMin} ${t('common.minShort')}`],
                            ['redBlue.cost', num(response.costIndex, 1)],
                          ] as const
                        ).map(([key, value]) => (
                          <div key={key} className="min-w-0">
                            <p className="truncate text-[10px] text-text-faint">{t(key)}</p>
                            <p className="font-mono text-[12px] font-semibold tabular-nums">
                              {value}
                            </p>
                          </div>
                        ))}
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </PanelBody>
          </Panel>
        </>
      ) : null}
    </div>
  )
}
