import { Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { factorDetail, factorLabel } from '@/lib/engine/explain'
import type { RiskAssessment } from '@/lib/engine/risk'
import { styleForRisk } from '@/lib/ui/state-styles'

/**
 * The "WHY?" panel (§8).
 *
 * Contributions are rendered as a proportion of the score they add up to, so the bars
 * are literally the score decomposed — not a separate importance ranking that happens to
 * sit next to it. That is the difference between an explanation and a decoration.
 */
export async function RiskExplanation({
  risk,
  narrative,
  modelVersion,
  className,
}: {
  risk: RiskAssessment
  narrative: string
  modelVersion?: string
  className?: string
}) {
  const { t, locale } = await getI18n()
  const factors = risk.topFactors.filter((factor) => factor.contribution > 0.05)
  const maxContribution = Math.max(...factors.map((factor) => factor.contribution), 1)

  return (
    <Panel className={className}>
      <PanelHeader
        title={t('predictions.explain.title')}
        subtitle={t('predictions.explain.subtitle')}
        action={
          <span className={`tnum text-2xl font-semibold ${styleForRisk(risk.score).text}`}>
            {formatNumber(locale, risk.score, { maximumFractionDigits: 0 })}%
          </span>
        }
      />
      <PanelBody>
        {factors.length === 0 ? (
          <p className="text-sm text-text-muted">{t('predictions.explain.noFactors')}</p>
        ) : (
          <ul className="space-y-4">
            {factors.map((factor) => (
              <li key={factor.key}>
                <div className="flex flex-wrap items-baseline justify-between gap-2">
                  <span className="text-sm font-medium text-text">
                    {factorLabel(factor.key, locale)}
                  </span>
                  <span className="tnum text-sm font-semibold text-brand">
                    +{formatNumber(locale, factor.contribution, { maximumFractionDigits: 1 })}
                  </span>
                </div>

                <div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-surface-3">
                  <div
                    className="h-full rounded-full bg-gradient-to-r from-brand/50 to-brand"
                    style={{ width: `${(factor.contribution / maxContribution) * 100}%` }}
                  />
                </div>

                <p className="mt-1.5 text-xs leading-relaxed text-text-muted">
                  {factorDetail(factor.key, locale)}{' '}
                  <span className="tnum text-text-faint">
                    ({t('predictions.explain.value')}:{' '}
                    {formatNumber(locale, factor.rawValue, { maximumFractionDigits: 1 })}
                    {factor.unit === 'idx' ? '' : ` ${factor.unit}`})
                  </span>
                </p>
              </li>
            ))}
          </ul>
        )}

        <div className="mt-5 rounded-lg border border-border bg-surface-2/50 p-4">
          <p className="mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-text-faint">
            {t('predictions.explain.narrative')}
          </p>
          <p className="text-sm leading-relaxed text-text">{narrative}</p>
        </div>

        <dl className="mt-4 grid grid-cols-2 gap-3 border-t border-border pt-4 text-xs sm:grid-cols-4">
          <div>
            <dt className="text-text-faint">{t('common.riskScore')}</dt>
            <dd className="tnum mt-0.5 font-medium text-text">
              {formatNumber(locale, risk.score, { maximumFractionDigits: 1 })}%
            </dd>
          </div>
          <div>
            <dt className="text-text-faint">{t('grid.stability.load')}</dt>
            <dd className="tnum mt-0.5 font-medium text-text">
              {formatNumber(locale, risk.stressIndex * 100, { maximumFractionDigits: 1 })}%
            </dd>
          </div>
          <div>
            <dt className="text-text-faint">{t('settings.groups.risk')}</dt>
            <dd className="tnum mt-0.5 font-medium text-text">
              ×{formatNumber(locale, risk.vulnerability, { maximumFractionDigits: 2 })}
            </dd>
          </div>
          {modelVersion ? (
            <div>
              <dt className="text-text-faint">{t('predictions.explain.modelVersion')}</dt>
              <dd className="mt-0.5 font-mono text-[11px] font-medium text-text">{modelVersion}</dd>
            </div>
          ) : null}
        </dl>
      </PanelBody>
    </Panel>
  )
}
