'use client'

import { useRouter } from 'next/navigation'
import { useState } from 'react'

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

/**
 * The list of frozen proofs, and the button that freezes one (4.1).
 *
 * "PROVE IT" is the demo's name for a single action: take everything the platform is
 * relying on for this asset right now — model version, twin version, data snapshot,
 * physics verdict, the whole event sequence — and freeze it into a record that can be
 * examined after the situation has moved on. The button calls the real endpoint and
 * navigates to whatever it produced; there is no prepared proof waiting behind it.
 */

export interface ProofSummaryView {
  code: string
  assetCode: string
  recommendation: string
  recommendationAr: string
  riskBefore: number
  riskAfter: number
  evidenceKind: string
  outcome: string
  createdAt: number
  frameCount: number
}

export function ProofList({
  initialProofs,
  defaultAsset,
  canCreate,
}: {
  initialProofs: ProofSummaryView[]
  defaultAsset: string
  canCreate: boolean
}) {
  const { t, locale } = useI18n()
  const router = useRouter()
  const [proofs, setProofs] = useState(initialProofs)
  const [asset, setAsset] = useState(defaultAsset)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

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

  const proveIt = async () => {
    setBusy(true)
    setError(null)
    try {
      const proof = await api.post<{ code: string }>(`/api/decisions/${asset}/proof`, {
        assetCode: asset,
      })
      const refreshed = await api.get<{ proofs: ProofSummaryView[] }>('/api/proofs?limit=20')
      setProofs(refreshed.proofs)
      router.push(`/proofs/${proof.code}`)
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : t('common.error'))
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="space-y-4" data-testid="proof-list">
      <Notice tone="info">{t('proof.note')}</Notice>

      {canCreate ? (
        <Panel>
          <PanelHeader title={t('proof.create')} />
          <PanelBody className="flex flex-wrap items-end gap-2">
            <label className="block">
              <span className="mb-1 block text-[11px] text-text-muted">{t('proof.asset')}</span>
              <input
                value={asset}
                onChange={(event) => setAsset(event.target.value.toUpperCase())}
                className="h-8 w-40 rounded-md border border-border bg-surface-2 px-2 font-mono text-xs text-text"
                aria-label={t('proof.asset')}
              />
            </label>
            <Button onClick={proveIt} disabled={busy || !asset} data-testid="prove-it">
              {busy ? t('proof.creating') : t('proof.proveIt')}
            </Button>
            {error ? <p className="text-[11px] text-critical">{error}</p> : null}
          </PanelBody>
        </Panel>
      ) : null}

      {proofs.length === 0 ? (
        <EmptyState title={t('uiState.empty')} body={t('proof.empty')} />
      ) : (
        <Panel>
          <PanelHeader title={t('proof.list')} />
          <PanelBody>
            <ul className="space-y-1.5">
              {proofs.map((proof) => (
                <li key={proof.code}>
                  <a
                    href={`/proofs/${proof.code}`}
                    data-proof={proof.code}
                    className="flex flex-wrap items-baseline justify-between gap-2 rounded-lg border border-border bg-surface-2/40 px-3 py-2 text-[12px] transition-colors hover:border-brand/30"
                  >
                    <span className="min-w-0">
                      <span className="me-2 font-mono text-[11px] text-text-faint">{proof.assetCode}</span>
                      {locale === 'ar' ? proof.recommendationAr : proof.recommendation}
                    </span>
                    <span className="flex items-center gap-2">
                      <Badge tone="accent">
                        {proof.evidenceKind === 'observed'
                          ? t('proof.evidenceObserved')
                          : t('proof.evidenceSimulated')}
                      </Badge>
                      <span className="font-mono tabular-nums text-text-faint">
                        {num(proof.riskBefore, 1)} → {num(proof.riskAfter, 1)} ·{' '}
                        {num(proof.frameCount)} {t('proof.frames')} ·{' '}
                        {formatDateTime(locale, proof.createdAt)}
                      </span>
                    </span>
                  </a>
                </li>
              ))}
            </ul>
          </PanelBody>
        </Panel>
      )}
    </div>
  )
}
