import { Badge, Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { cn } from '@/lib/cn'
import type { ScoredStrategy } from '@/lib/engine/optimize'

/**
 * Strategy comparison (§11, §12, §24).
 *
 * The objective terms are folded under each row rather than summarised away: "why did
 * this one win" is answerable only by seeing the terms that separated it from the one
 * below it.
 */
export async function StrategyTable({
  strategies,
  className,
  title,
  subtitle,
}: {
  strategies: ScoredStrategy[]
  className?: string
  title?: string
  subtitle?: string
}) {
  const { t, locale } = await getI18n()
  const ar = locale === 'ar'

  return (
    <Panel className={className}>
      <PanelHeader
        title={title ?? t('selfHealing.title')}
        subtitle={subtitle ?? t('selfHealing.subtitle')}
        action={<Badge tone="accent">{t('common.simulationOnly')}</Badge>}
      />
      <PanelBody className="space-y-3 pt-0">
        {strategies.map((strategy) => (
          <div
            key={strategy.key}
            className={cn(
              'rounded-[--radius-panel] border p-3.5',
              strategy.isRecommended
                ? 'border-brand/45 bg-brand/6'
                : 'border-border bg-surface-2/40',
            )}
          >
            <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2">
              <div className="min-w-0">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="tnum text-[10px] font-semibold text-text-faint">#{strategy.rank}</span>
                  <p className="text-sm font-medium text-text">{ar ? strategy.labelAr : strategy.label}</p>
                  {strategy.isRecommended ? (
                    <Badge tone="brand">{t('selfHealing.recommended')}</Badge>
                  ) : null}
                </div>
                <p className="tnum mt-1 text-[11px] text-text-muted">
                  {t('selfHealing.riskAfter')}{' '}
                  <span className="text-text-faint line-through">
                    {formatNumber(locale, strategy.evaluation.riskBefore, { maximumFractionDigits: 0 })}%
                  </span>{' '}
                  <span className="font-medium text-normal">
                    {formatNumber(locale, strategy.evaluation.riskAfter, { maximumFractionDigits: 0 })}%
                  </span>
                  {' · '}
                  {t('selfHealing.cost')} {formatNumber(locale, strategy.costSar)} {t('common.sar')}
                  {' · '}
                  {t('selfHealing.executionTime')} {formatNumber(locale, strategy.executionMin)}{' '}
                  {t('common.minutes')}
                  {' · '}
                  {t('selfHealing.customerImpact')} {formatNumber(locale, strategy.customerImpact)}
                </p>
              </div>
              <div className="text-end">
                <p className="tnum text-xl font-semibold text-text">
                  {formatNumber(locale, strategy.score, { maximumFractionDigits: 1 })}
                </p>
                <p className="text-[10px] text-text-faint">{t('selfHealing.score')}</p>
              </div>
            </div>

            <details className="group mt-2.5 border-t border-border/60 pt-2.5">
              <summary className="cursor-pointer list-none text-[11px] font-medium text-brand transition-colors hover:underline">
                {t('selfHealing.terms')}
              </summary>
              <div className="mt-2 overflow-x-auto">
                <table className="w-full min-w-[26rem] text-[11px]">
                  <thead>
                    <tr className="border-b border-border/60 text-[10px] uppercase tracking-wide text-text-faint">
                      <th className="py-1.5 text-start font-medium">{t('objective.title')}</th>
                      <th className="py-1.5 text-end font-medium">{t('objective.value')}</th>
                      <th className="py-1.5 text-end font-medium">{t('objective.normalised')}</th>
                      <th className="py-1.5 text-end font-medium">{t('objective.weight')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {strategy.metrics.map((metric) => (
                      <tr key={metric.key} className="border-b border-border/40 last:border-0">
                        <td className="py-1.5 text-text-muted">{t(`selfHealing.metric.${metric.key}`)}</td>
                        <td className="tnum py-1.5 text-end text-text">
                          {formatNumber(locale, metric.value, { maximumFractionDigits: 1 })} {metric.unit}
                        </td>
                        <td className="tnum py-1.5 text-end text-text-muted">
                          {formatNumber(locale, metric.normalised * 100, { maximumFractionDigits: 0 })}%
                        </td>
                        <td className="tnum py-1.5 text-end text-text-faint">
                          {formatNumber(locale, metric.weight * 100, { maximumFractionDigits: 0 })}%
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                <p className="mt-2 text-[10px] leading-relaxed text-text-faint">{t('objective.hint')}</p>
              </div>
            </details>
          </div>
        ))}

        <p className="rounded-lg border border-accent/25 bg-accent/6 px-3 py-2 text-[11px] leading-relaxed text-accent">
          {t('selfHealing.simulationOnly')}
        </p>
      </PanelBody>
    </Panel>
  )
}
