'use client'

import { useState } from 'react'

import { Button, Dialog } from '@/components/ui/controls'
import { Badge } 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'
import { EvidenceChain, type EvidenceBundleView } from './evidence-chain'

/**
 * "Why should I trust this?" (§109) and PROVE IT (§51).
 *
 * One button, two audiences. A judge presses it to interrogate a claim; an operator
 * presses it because they are about to act on one. Both get the same thing: the actual
 * chain, with every source labelled and the weakest link named.
 *
 * The chain is fetched on open rather than rendered with the page. It is the most
 * expensive read in the console and almost nobody opens it — paying for it on every page
 * load to save a second for the few who do is the wrong trade.
 */

export function TrustDialog({
  assetCode,
  twinCode,
  label,
  variant = 'secondary',
}: {
  assetCode: string
  twinCode?: string | null
  label?: string
  variant?: 'primary' | 'secondary' | 'ghost'
}) {
  const { t, locale } = useI18n()
  const [open, setOpen] = useState(false)
  const [bundle, setBundle] = useState<EvidenceBundleView | null>(null)
  const [summary, setSummary] = useState<{
    modelVersion: string
    twinVersion: string
    dataSnapshotId: string
    seedNote: string
  } | null>(null)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const load = async () => {
    setOpen(true)
    if (bundle || busy) return
    setBusy(true)
    setError(null)
    try {
      const result = await api.post<{
        bundle: EvidenceBundleView
        reproducibility: {
          modelVersion: string
          twinVersion: string
          dataSnapshotId: string
          seedNote: string
        }
      }>('/api/evidence', { assetCode, twinCode: twinCode ?? null })
      setBundle(result.bundle)
      setSummary(result.reproducibility)
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : t('common.error'))
    } finally {
      setBusy(false)
    }
  }

  return (
    <>
      <Button variant={variant} onClick={load}>
        {label ?? t('trustMe.open')}
      </Button>

      <Dialog
        open={open}
        onClose={() => setOpen(false)}
        title={t('trustMe.title')}
        description={t('trustMe.subtitle')}
        closeLabel={t('common.close')}
        size="lg"
      >
        {busy ? (
          <p className="py-6 text-center text-[12px] text-text-muted">{t('common.running')}</p>
        ) : error ? (
          <p className="py-6 text-center text-[12px] text-critical">{error}</p>
        ) : bundle ? (
          <div className="space-y-3">
            <div className="flex flex-wrap items-center gap-2">
              <Badge tone="muted">
                {t('evidence.measured')}:{' '}
                {formatNumber(locale, bundle.measuredSharePct, { maximumFractionDigits: 0 })}%
              </Badge>
              {bundle.weakestLink ? (
                <Badge tone="accent">
                  {t('evidence.weakestLink')}:{' '}
                  {locale === 'ar' ? bundle.weakestLink.titleAr : bundle.weakestLink.title}{' '}
                  {formatNumber(locale, bundle.weakestLink.confidence, { maximumFractionDigits: 0 })}%
                </Badge>
              ) : null}
            </div>

            <EvidenceChain bundle={bundle} />

            {summary ? (
              <div className="rounded-lg border border-border bg-surface-2/50 px-3 py-2">
                <p className="text-[10px] font-medium text-text-faint">
                  {t('evidence.reproducible')}
                </p>
                <p
                  className={cn(
                    'mt-0.5 font-mono text-[10px] break-all text-text-muted',
                    'leading-relaxed',
                  )}
                >
                  {summary.modelVersion} · {summary.twinVersion || '—'} · {summary.dataSnapshotId}
                </p>
                <p className="mt-1 text-[10px] leading-relaxed text-text-faint">
                  {t('evidence.reproducibleNote')}
                </p>
              </div>
            ) : null}
          </div>
        ) : null}
      </Dialog>
    </>
  )
}
