import Link from 'next/link'

import { Badge, Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { DNA_FEATURES, type DnaMatch } from '@/lib/engine/dna'
import type { DnaPatternRef } from '@/lib/engine/grid'
import { styleForRisk } from '@/lib/ui/state-styles'

/**
 * Failure DNA matches (§4).
 *
 * The top match is expanded dimension by dimension. That expansion is the point: a
 * similarity percentage on its own is an assertion, while "these seven dimensions agree
 * closely and these three do not" is something an engineer can argue with.
 */
export async function DnaMatchPanel({
  matches,
  className,
  compact = false,
}: {
  matches: Array<DnaMatch<DnaPatternRef>>
  className?: string
  compact?: boolean
}) {
  const { t, locale } = await getI18n()

  if (matches.length === 0) {
    return (
      <Panel className={className}>
        <PanelHeader title={t('dna.topMatches')} />
        <PanelBody>
          <p className="text-sm text-text-muted">{t('dna.empty')}</p>
        </PanelBody>
      </Panel>
    )
  }

  const [top, ...rest] = matches

  return (
    <Panel className={className}>
      <PanelHeader
        title={t('dna.topMatches')}
        subtitle={compact ? undefined : t('dna.howItWorksBody')}
        action={
          <Link href="/failure-dna" className="text-xs font-medium text-brand hover:underline">
            {t('common.viewAll')}
          </Link>
        }
      />

      <PanelBody>
        {/* Top match */}
        <div className="rounded-lg border border-brand/30 bg-brand/6 p-4">
          <div className="flex flex-wrap items-start justify-between gap-3">
            <div className="min-w-0">
              <div className="flex flex-wrap items-center gap-2">
                <Badge tone="brand">{top.pattern.code}</Badge>
                <span className="text-[11px] text-text-muted">
                  {t(`eventType.${top.pattern.eventType}`)}
                </span>
              </div>
              <p className="mt-2 text-sm font-medium text-text">
                {locale === 'ar' ? top.pattern.nameAr : top.pattern.name}
              </p>
            </div>

            <div className="text-end">
              <p className="text-[10px] uppercase tracking-wide text-text-faint">
                {t('dna.similarity')}
              </p>
              <p className={`tnum text-3xl font-semibold ${styleForRisk(top.similarity).text}`}>
                {formatNumber(locale, top.similarity, { maximumFractionDigits: 0 })}%
              </p>
            </div>
          </div>

          {/* Dimension-by-dimension comparison */}
          <div className="mt-4 space-y-1.5 border-t border-brand/20 pt-4">
            <div className="flex items-center gap-3 text-[10px] uppercase tracking-wide text-text-faint">
              <span className="w-32 shrink-0">{t('dna.dimensions')}</span>
              <span className="flex-1">{t('dna.current')} / {t('dna.historical')}</span>
              <span className="w-12 text-end">{t('dna.agreement')}</span>
            </div>

            {top.contributions.map((entry) => (
              <div key={entry.feature} className="flex items-center gap-3">
                <span className="w-32 shrink-0 truncate text-[11px] text-text-muted">
                  {t(`dnaFeature.${entry.feature}`)}
                </span>

                <div className="relative h-4 flex-1 overflow-hidden rounded bg-surface-3">
                  <div
                    className="absolute inset-y-0 rounded bg-info/45"
                    style={{ insetInlineStart: 0, width: `${entry.historical * 100}%` }}
                    title={t('dna.historical')}
                  />
                  <div
                    className="absolute inset-y-1 rounded bg-brand"
                    style={{ insetInlineStart: 0, width: `${entry.current * 100}%` }}
                    title={t('dna.current')}
                  />
                </div>

                <span
                  className={`tnum w-12 shrink-0 text-end text-[11px] font-medium ${
                    entry.agreement >= 85
                      ? 'text-normal'
                      : entry.agreement >= 60
                        ? 'text-watch'
                        : 'text-text-faint'
                  }`}
                >
                  {formatNumber(locale, entry.agreement, { maximumFractionDigits: 0 })}%
                </span>
              </div>
            ))}
          </div>

          <div className="mt-4 flex flex-wrap items-center gap-3 border-t border-brand/20 pt-3 text-[11px] text-text-muted">
            <span className="flex items-center gap-1.5">
              <span className="size-2 rounded-sm bg-brand" /> {t('dna.current')}
            </span>
            <span className="flex items-center gap-1.5">
              <span className="size-2 rounded-sm bg-info/45" /> {t('dna.historical')}
            </span>
          </div>
        </div>

        {/* Runners-up */}
        {rest.length > 0 ? (
          <ul className="mt-3 space-y-2">
            {rest.map((match) => (
              <li
                key={match.pattern.code}
                className="flex items-center justify-between gap-3 rounded-lg border border-border bg-surface-2/40 px-3 py-2.5"
              >
                <div className="min-w-0">
                  <span className="font-mono text-[11px] text-text-muted">{match.pattern.code}</span>
                  <p className="truncate text-xs text-text">
                    {locale === 'ar' ? match.pattern.nameAr : match.pattern.name}
                  </p>
                </div>
                <span className="tnum shrink-0 text-sm font-medium text-text-muted">
                  {formatNumber(locale, match.similarity, { maximumFractionDigits: 0 })}%
                </span>
              </li>
            ))}
          </ul>
        ) : null}

        <p className="mt-4 text-[11px] leading-relaxed text-text-faint">
          {DNA_FEATURES.length} {t('dna.dimensions').toLowerCase()} · {t('common.simulatedFull')}
        </p>
      </PanelBody>
    </Panel>
  )
}
