'use client'

import { useState } from 'react'

import { Badge, EmptyState, Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { useI18n } from '@/components/providers/i18n-provider'
import { formatNumber } from '@/lib/i18n/translate'
import { cn } from '@/lib/cn'

/**
 * "Have we seen this before?" (§29).
 *
 * The similarity figure is expandable into the per-field contributions that produced it,
 * because an operator told "91 % similar" with no way to check will — correctly — ignore
 * it. Being able to see that the match is driven by an unusual DNA hit rather than by
 * both units happening to be transformers is what makes the number worth anything.
 *
 * Every row carries its evidence kind. A simulated outcome and an observed one are
 * different claims and are never presented as the same one (§30).
 */

export interface SimilarMatchView {
  code: string
  title: string
  titleAr: string
  similarity: number
  strategyLabel: string
  strategyLabelAr: string
  riskBefore: number
  riskAfter: number
  outcomeStatus: string
  evidenceKind: string
  evidenceLabel: string
  evidenceLabelAr: string
  headline: string
  headlineAr: string
  contributions: Array<{
    key: string
    label: string
    labelAr: string
    weight: number
    agreement: number
    detail: string
    detailAr: string
  }>
}

const OUTCOME_TONE: Record<string, 'brand' | 'info' | 'accent' | 'muted'> = {
  prevented: 'brand',
  occurred: 'accent',
  partial: 'info',
  pending: 'muted',
  not_observed: 'muted',
}

export function SimilarDecisions({ matches }: { matches: SimilarMatchView[] }) {
  const { t, locale } = useI18n()
  const [expanded, setExpanded] = useState<string | null>(null)

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

  return (
    <Panel>
      <PanelHeader title={t('memory.similar')} subtitle={t('memory.similarSubtitle')} />
      <PanelBody>
        {matches.length === 0 ? (
          <EmptyState title={t('uiState.empty')} body={t('memory.noMatches')} />
        ) : (
          <ul className="space-y-2">
            {matches.map((match) => {
              const open = expanded === match.code
              return (
                <li key={match.code} className="min-w-0 rounded-lg border border-border">
                  <button
                    type="button"
                    onClick={() => setExpanded(open ? null : match.code)}
                    aria-expanded={open}
                    className="w-full min-w-0 px-3 py-2.5 text-start transition-colors hover:bg-surface-2"
                  >
                    <div className="flex flex-wrap items-baseline gap-2">
                      <span className="min-w-0 flex-1 truncate text-[12px] font-medium">
                        {locale === 'ar' ? match.titleAr : match.title}
                      </span>
                      <span className="shrink-0 font-mono text-sm font-semibold tabular-nums text-brand">
                        {num(match.similarity)}%
                      </span>
                    </div>

                    <div className="mt-1 flex flex-wrap items-center gap-1.5">
                      <Badge tone={OUTCOME_TONE[match.outcomeStatus] ?? 'muted'} dot>
                        {t(`memory.result.${match.outcomeStatus}`)}
                      </Badge>
                      <Badge tone={match.evidenceKind === 'observed' ? 'brand' : 'muted'}>
                        {t(`common.${match.evidenceKind}`)}
                      </Badge>
                      <span className="text-[10px] text-text-faint">
                        {locale === 'ar' ? match.strategyLabelAr : match.strategyLabel} ·{' '}
                        <span className="font-mono tabular-nums">
                          {num(match.riskBefore)}% → {num(match.riskAfter)}%
                        </span>
                      </span>
                    </div>

                    <p className="mt-1 text-[10px] leading-relaxed text-text-muted">
                      {locale === 'ar' ? match.headlineAr : match.headline}
                    </p>
                  </button>

                  {open ? (
                    <div className="border-t border-border px-3 py-2">
                      <p className="mb-1.5 text-[10px] font-medium text-text-faint">
                        {t('memory.whyMatch')}
                      </p>
                      <ul className="space-y-1">
                        {[...match.contributions]
                          .sort((a, b) => b.agreement * b.weight - a.agreement * a.weight)
                          .map((contribution) => (
                            <li key={contribution.key} className="flex items-center gap-2 text-[10px]">
                              <span className="w-24 shrink-0 truncate text-text-faint">
                                {locale === 'ar' ? contribution.labelAr : contribution.label}
                              </span>
                              <span className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-surface-3">
                                <span
                                  className={cn(
                                    'block h-full rounded-full',
                                    contribution.agreement > 0.6 ? 'bg-brand' : 'bg-info/60',
                                  )}
                                  style={{ width: `${Math.max(1, contribution.agreement * 100)}%` }}
                                />
                              </span>
                              <span className="w-32 shrink-0 truncate text-end text-text-muted">
                                {locale === 'ar' ? contribution.detailAr : contribution.detail}
                              </span>
                            </li>
                          ))}
                      </ul>

                      <p className="mt-2 text-[10px] leading-relaxed text-text-faint">
                        {locale === 'ar' ? match.evidenceLabelAr : match.evidenceLabel}
                      </p>
                    </div>
                  ) : null}
                </li>
              )
            })}
          </ul>
        )}
      </PanelBody>
    </Panel>
  )
}
