'use client'

import { Badge, 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'

/**
 * The impact panel (§55, §56, §57).
 *
 * Four families, kept apart on screen exactly as they are kept apart in the engine. There
 * is no combined total, because summing megawatts with riyals produces a number that
 * looks authoritative and means nothing.
 *
 * The financial figure carries the lowest confidence in the set and its assumptions are
 * printed underneath it rather than buried. A saving whose tariff is hidden cannot be
 * argued with, and a number that cannot be argued with should not be on a dashboard.
 */

export interface ImpactFigureView {
  key: string
  label: string
  labelAr: string
  value: number
  unit: string
  unitAr: string
  evidenceKind: string
  confidence: number
  confidenceBand: string
  detail: string
  detailAr: string
}

export interface ImpactView {
  technical: ImpactFigureView[]
  operational: ImpactFigureView[]
  customer: ImpactFigureView[]
  financial: ImpactFigureView[]
  maintenance: ImpactFigureView[]
  assumptions: Array<{ key: string; label: string; labelAr: string; value: string }>
  impactScore: number
  impactComponents: Array<{ key: string; label: string; labelAr: string; value: number; weight: number }>
}

const EVIDENCE_TONE: Record<string, string> = {
  observed: 'border-normal/35 bg-normal/12 text-normal',
  simulated: 'border-simulation/35 bg-simulation/12 text-simulation',
  projected: 'border-accent/35 bg-accent/12 text-accent',
}

const BAND_TONE: Record<string, string> = {
  high: 'text-normal',
  medium: 'text-watch',
  low: 'text-warning',
}

function FigureRow({ figure }: { figure: ImpactFigureView }) {
  const { t, locale } = useI18n()
  const label = locale === 'ar' ? figure.labelAr : figure.label
  const unit = locale === 'ar' ? figure.unitAr : figure.unit

  return (
    <li className="min-w-0 border-t border-border/60 py-2 first:border-t-0 first:pt-0">
      <div className="flex flex-wrap items-baseline gap-2">
        <span className="min-w-0 flex-1 text-[11px] text-text-muted">{label}</span>
        <span className="shrink-0 font-mono text-sm font-semibold tabular-nums">
          {formatNumber(locale, figure.value, { maximumFractionDigits: 1 })}
          <span className="ms-1 text-[10px] font-normal text-text-faint">{unit}</span>
        </span>
      </div>
      <div className="mt-1 flex flex-wrap items-center gap-1.5">
        <span
          className={cn(
            'rounded-full border px-1.5 py-0.5 text-[9px] font-medium',
            EVIDENCE_TONE[figure.evidenceKind] ?? EVIDENCE_TONE.projected,
          )}
        >
          {t(`common.${figure.evidenceKind}`)}
        </span>
        <span className={cn('text-[10px]', BAND_TONE[figure.confidenceBand] ?? 'text-text-faint')}>
          {t('common.confidence')}: {t(`confidence.${figure.confidenceBand}`)}
        </span>
      </div>
      <p className="mt-0.5 text-[10px] leading-relaxed text-text-faint">
        {locale === 'ar' ? figure.detailAr : figure.detail}
      </p>
    </li>
  )
}

export function ImpactPanel({ impact }: { impact: ImpactView }) {
  const { t, locale } = useI18n()

  const families = [
    { key: 'technical', figures: impact.technical },
    { key: 'operational', figures: impact.operational },
    { key: 'customer', figures: impact.customer },
    { key: 'maintenance', figures: impact.maintenance },
    { key: 'financial', figures: impact.financial },
  ].filter((family) => family.figures.length > 0)

  return (
    <Panel>
      <PanelHeader
        title={t('impact.title')}
        subtitle={t('impact.subtitle')}
        action={
          <Badge tone="muted">
            {t('impact.score')}:{' '}
            {formatNumber(locale, impact.impactScore, { maximumFractionDigits: 0 })}
          </Badge>
        }
      />
      <PanelBody className="space-y-4">
        {families.map((family) => (
          <div key={family.key} className="min-w-0">
            <p className="mb-1 text-[11px] font-semibold text-text">{t(`impact.${family.key}`)}</p>
            <ul>
              {family.figures.map((figure) => (
                <FigureRow key={figure.key} figure={figure} />
              ))}
            </ul>
          </div>
        ))}

        {/* ── How the composite is built (§57) ──────────────────────────────── */}
        <div>
          <p className="mb-1 text-[11px] font-semibold text-text">{t('impact.howScored')}</p>
          <ul className="space-y-1">
            {impact.impactComponents.map((component) => (
              <li key={component.key} className="flex items-center gap-2 text-[11px]">
                <span className="min-w-0 flex-1 truncate text-text-muted">
                  {locale === 'ar' ? component.labelAr : component.label}
                </span>
                <span className="shrink-0 font-mono tabular-nums text-text-faint">
                  ×{formatNumber(locale, component.weight, { maximumFractionDigits: 2 })}
                </span>
                <span className="w-10 shrink-0 text-end font-mono tabular-nums">
                  {formatNumber(locale, component.value, { maximumFractionDigits: 0 })}
                </span>
              </li>
            ))}
          </ul>
        </div>

        {/* ── Assumptions, stated rather than buried (§55) ──────────────────── */}
        <div className="rounded-lg border border-border bg-surface-2/50 px-3 py-2">
          <p className="mb-1 text-[11px] font-semibold text-text-muted">{t('impact.assumptions')}</p>
          <dl className="space-y-0.5">
            {impact.assumptions.map((assumption) => (
              <div key={assumption.key} className="flex flex-wrap justify-between gap-2 text-[10px]">
                <dt className="text-text-faint">
                  {locale === 'ar' ? assumption.labelAr : assumption.label}
                </dt>
                <dd className="text-text-muted">{assumption.value}</dd>
              </div>
            ))}
          </dl>
        </div>
      </PanelBody>
    </Panel>
  )
}
