import { Badge, Meter, 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 { WeakSignalResult } from '@/lib/engine/weak-signal'

/**
 * Weak signal detection (§33) and the lead-time claim it supports (§34).
 *
 * The "no conventional alarm has fired" line is the load-bearing one: without it the
 * panel is just another deviation table, and with it the reader can see that the
 * platform is looking at something a threshold cannot.
 */
export async function WeakSignalsPanel({
  result,
  leadMinutes,
  className,
}: {
  result: WeakSignalResult
  leadMinutes?: number | null
  className?: string
}) {
  const { t, locale } = await getI18n()

  return (
    <Panel className={className}>
      <PanelHeader
        title={t('weakSignals.title')}
        subtitle={t('weakSignals.subtitle')}
        action={
          <Badge tone={result.isPattern ? 'accent' : 'muted'}>
            {result.isPattern ? t('weakSignals.patternFound') : t('weakSignals.noPattern')}
          </Badge>
        }
      />
      <PanelBody className="pt-0">
        <Meter
          value={result.combinedScore}
          state={result.combinedScore >= 70 ? 'critical' : result.combinedScore >= 45 ? 'warning' : 'watch'}
          label={t('weakSignals.combined')}
          showValue
        />

        <p
          className={cn(
            'mt-3 rounded-lg border px-3 py-2 text-[11px] leading-relaxed',
            result.traditionalAlarm
              ? 'border-critical/30 bg-critical/8 text-critical'
              : 'border-brand/30 bg-brand/8 text-brand',
          )}
        >
          {result.traditionalAlarm ? t('weakSignals.traditionalSounding') : t('weakSignals.traditionalSilent')}
          {typeof leadMinutes === 'number' && leadMinutes > 0
            ? ` — ${t('weakSignals.leadTime')} ${formatNumber(locale, leadMinutes)} ${t('common.minutes')}`
            : ''}
        </p>

        <div className="mt-3 overflow-x-auto">
          <table className="w-full min-w-[30rem] text-xs">
            <thead>
              <tr className="border-b border-border text-[10px] uppercase tracking-wide text-text-faint">
                <th className="py-2 text-start font-medium">{t('weakSignals.channel')}</th>
                <th className="py-2 text-end font-medium">{t('weakSignals.observed')}</th>
                <th className="py-2 text-end font-medium">{t('weakSignals.expected')}</th>
                <th className="py-2 text-end font-medium">{t('weakSignals.deviation')}</th>
                <th className="py-2 text-end font-medium">{t('weakSignals.threshold')}</th>
              </tr>
            </thead>
            <tbody>
              {result.signals.map((signal) => (
                <tr key={signal.key} className="border-b border-border/50 last:border-0">
                  <td className="py-2 text-text">{t(`weakSignals.key.${signal.key}`)}</td>
                  <td className="tnum py-2 text-end text-text-muted">
                    {formatNumber(locale, signal.observed, { maximumFractionDigits: 1 })} {signal.unit}
                  </td>
                  <td className="tnum py-2 text-end text-text-muted">
                    {formatNumber(locale, signal.expected, { maximumFractionDigits: 1 })} {signal.unit}
                  </td>
                  <td
                    className={cn(
                      'tnum py-2 text-end font-medium',
                      signal.isIndividuallyCritical
                        ? 'text-critical'
                        : signal.deviationPct > 0
                          ? 'text-watch'
                          : 'text-normal',
                    )}
                  >
                    {signal.deviationPct > 0 ? '+' : ''}
                    {formatNumber(locale, signal.deviationPct, { maximumFractionDigits: 1 })}%
                  </td>
                  <td className="tnum py-2 text-end text-text-faint">
                    {formatNumber(locale, signal.individualThresholdPct)}%
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </PanelBody>
    </Panel>
  )
}
