'use client'

import { useI18n } from '@/components/providers/i18n-provider'
import { Badge, Meter, Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { cn } from '@/lib/cn'

/**
 * Twin fidelity, freshness and deviation (§31–§33).
 *
 * The three belong on one panel because they answer one question in three parts: how
 * much of this twin is measurement, how recently it was measured, and where the
 * measurement and the model disagree. A twin that shows its state without showing its
 * fidelity is asking to be trusted more than it has earned.
 */
export interface FidelityView {
  score: number
  band: string
  sensorCoverage: number
  dataFreshness: number
  sensorTrust: number
  modelCoverage: number
  historicalDepth: number
  msSinceLastSync: number
  sensorsOnline: number
  sensorsExpected: number
  warning: string | null
  warningAr: string | null
}

export interface DeviationView {
  assetCode: string
  channel: string
  expected: number
  observed: number
  deviationPct: number
  cause: string
  confidence: number
  detail: string
  detailAr: string
}

const FACTORS = ['sensorCoverage', 'dataFreshness', 'sensorTrust', 'modelCoverage', 'historicalDepth'] as const

function stateFor(value: number) {
  if (value >= 85) return 'normal' as const
  if (value >= 65) return 'watch' as const
  if (value >= 45) return 'warning' as const
  return 'critical' as const
}

export function FidelityPanel({
  fidelity,
  deviations,
  className,
}: {
  fidelity: FidelityView
  deviations: DeviationView[]
  className?: string
}) {
  const { t, locale, n } = useI18n()
  const ar = locale === 'ar'
  const seconds = fidelity.msSinceLastSync / 1000

  return (
    <Panel className={className}>
      <PanelHeader
        title={t('twin.fidelity')}
        subtitle={t('twin.fidelityHint')}
        action={<Badge tone={fidelity.score >= 75 ? 'brand' : 'accent'}>{t(`twin.fidelityBand.${fidelity.band}`)}</Badge>}
      />
      <PanelBody className="space-y-3 pt-0">
        <div className="flex items-baseline gap-2 border-b border-border/70 pb-3">
          <p className="type-data text-text">{n(fidelity.score, { maximumFractionDigits: 0 })}%</p>
          <p className="text-xs text-text-muted">{t('twin.fidelity')}</p>
        </div>

        {FACTORS.map((factor) => (
          <Meter
            key={factor}
            value={fidelity[factor]}
            state={stateFor(fidelity[factor])}
            label={t(`twin.fidelityFactor.${factor}`)}
            showValue
          />
        ))}

        <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 border-t border-border/70 pt-3 text-[11px]">
          <span className="text-text-muted">
            {t('twin.lastSync')}:{' '}
            <span className={cn('tnum font-medium', seconds > 900 ? 'text-watch' : 'text-text')}>
              {seconds < 90
                ? `${n(seconds, { maximumFractionDigits: 1 })} s`
                : `${n(seconds / 60, { maximumFractionDigits: 1 })} min`}
            </span>
          </span>
          <span className="tnum text-text-muted">
            {t('twin.sensorsOnline')}: {n(fidelity.sensorsOnline)} / {n(fidelity.sensorsExpected)}
          </span>
        </div>

        {fidelity.warning ? (
          <p className="rounded-lg border border-watch/30 bg-watch/8 px-3 py-2 text-[11px] leading-relaxed text-watch">
            {ar ? fidelity.warningAr : fidelity.warning}
          </p>
        ) : null}

        <div className="border-t border-border/70 pt-3">
          <p className="text-[10px] uppercase tracking-wide text-text-faint">{t('twin.deviation')}</p>
          <p className="mt-0.5 text-[11px] leading-relaxed text-text-muted">{t('twin.deviationHint')}</p>

          {deviations.length === 0 ? (
            <p className="mt-2 text-[11px] text-normal">{t('twin.deviationNone')}</p>
          ) : (
            <ul className="mt-2 space-y-2">
              {deviations.slice(0, 5).map((deviation, index) => (
                <li
                  key={`${deviation.assetCode}-${deviation.channel}-${index}`}
                  className="rounded-lg border border-border bg-surface-2/40 p-2.5"
                >
                  <div className="flex flex-wrap items-baseline justify-between gap-2">
                    <span className="font-mono text-[11px] text-text">
                      {deviation.assetCode} · {deviation.channel}
                    </span>
                    <span
                      className={cn(
                        'tnum text-[11px] font-medium',
                        Math.abs(deviation.deviationPct) > 15 ? 'text-critical' : 'text-watch',
                      )}
                    >
                      {deviation.deviationPct > 0 ? '+' : ''}
                      {n(deviation.deviationPct, { maximumFractionDigits: 1 })}%
                    </span>
                  </div>
                  <p className="tnum mt-1 text-[10px] text-text-faint">
                    {t('twin.expected')} {n(deviation.expected, { maximumFractionDigits: 1 })} ·{' '}
                    {t('twin.observed')} {n(deviation.observed, { maximumFractionDigits: 1 })}
                  </p>
                  <p className="mt-1 text-[11px] leading-relaxed text-text-muted">
                    <span className="font-medium text-accent">{t(`twin.cause.${deviation.cause}`)}</span>{' '}
                    — {ar ? deviation.detailAr : deviation.detail}
                  </p>
                </li>
              ))}
            </ul>
          )}
        </div>
      </PanelBody>
    </Panel>
  )
}
