import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import {
  Badge,
  DemoDataBadge,
  EmptyState,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StatCard,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { getDataHealth } from '@/lib/services/data-health-service'
import { cn } from '@/lib/cn'

export const metadata: Metadata = { title: 'Data Health' }
export const dynamic = 'force-dynamic'

const TRUST_TONE: Record<string, string> = {
  trusted: 'text-normal',
  usable: 'text-watch',
  suspect: 'text-warning',
  untrusted: 'text-critical',
}

const VERDICT_TONE: Record<string, 'brand' | 'info' | 'accent' | 'muted'> = {
  consistent: 'brand',
  sensor_suspect: 'accent',
  model_suspect: 'info',
  asset_behaviour: 'info',
  insufficient_reference: 'muted',
}

/**
 * The Data Health Command Center (§78, §79, §80).
 *
 * Two questions with different remedies, answered separately: is the instrumentation
 * working, and is it telling the truth. The second only became answerable in 4.0, and it
 * is the more valuable of the two — a sensor that reports cleanly and is wrong is
 * invisible to every check that looks only at its own record.
 */
export default async function DataHealthPage() {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('datahealth.read')) return <PermissionGate />

  const health = await getDataHealth({ limit: 40 })
  const num = (value: number, digits = 1) =>
    formatNumber(locale, value, { maximumFractionDigits: digits })

  const cross = health.crossValidation

  return (
    <>
      <PageHeader
        title={t('dataHealth.title')}
        subtitle={t('dataHealth.subtitle')}
        badge={<DemoDataBadge label={t('source.synthetic')} title={t('common.simulatedTooltip')} />}
      />

      <div className="space-y-4">
        <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
          <StatCard
            label={t('dataHealth.online')}
            value={`${health.sensorsOnline} / ${health.sensorsTotal}`}
            hint={`${num(health.coveragePct)}% ${t('dataHealth.coverage').toLowerCase()}`}
          />
          <StatCard label={t('dataHealth.meanTrust')} value={`${num(health.meanTrust)}`} />
          <StatCard
            label={t('dataHealth.lowTrust')}
            value={health.sensorsLowTrust}
            hint={`${health.sensorsOffline} ${t('dataHealth.offline').toLowerCase()}`}
          />
          <StatCard
            label={t('dataHealth.overdueCalibration')}
            value={health.overdueCalibration}
            hint={`${num(health.meanLatencyMin)} ${t('common.minShort')} ${t('dataHealth.latency').toLowerCase()}`}
          />
        </div>

        {/* ── Cross-sensor validation (§80) ─────────────────────────────────── */}
        <Panel>
          <PanelHeader
            title={t('dataHealth.crossValidation')}
            subtitle={t('dataHealth.crossSubtitle')}
            action={
              <Badge tone="muted">
                {t('dataHealth.corroborated')}: {num(cross.corroboratedPct)}%
              </Badge>
            }
          />
          <PanelBody className="space-y-3">
            <p className="text-[12px] leading-relaxed">
              {locale === 'ar' ? cross.headlineAr : cross.headline}
            </p>

            <div className="grid grid-cols-2 gap-2 sm:grid-cols-5">
              {(
                [
                  ['consistent', cross.consistent],
                  ['sensor_suspect', cross.sensorSuspect],
                  ['model_suspect', cross.modelSuspect],
                  ['asset_behaviour', cross.assetBehaviour],
                  ['insufficient_reference', cross.unverifiable],
                ] as const
              ).map(([key, value]) => (
                <div key={key} className="min-w-0 rounded-lg border border-border bg-surface-2/50 p-2">
                  <p className="truncate text-[10px] text-text-faint">
                    {t(`dataHealth.verdict.${key}`)}
                  </p>
                  <p className="font-mono text-lg font-semibold tabular-nums">{value}</p>
                </div>
              ))}
            </div>
          </PanelBody>
        </Panel>

        {/* ── The instruments ───────────────────────────────────────────────── */}
        <Panel>
          <PanelHeader
            title={t('dataHealth.sensor')}
            subtitle={`${health.missingReadings.toLocaleString('en')} ${t('dataHealth.missing').toLowerCase()}`}
          />
          <PanelBody>
            {health.rows.length === 0 ? (
              <EmptyState title={t('uiState.empty')} body={t('dataHealth.subtitle')} />
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full min-w-[46rem] text-[11px]">
                  <thead>
                    <tr className="text-text-faint">
                      <th className="py-1.5 text-start font-medium">{t('dataHealth.sensor')}</th>
                      <th className="py-1.5 text-start font-medium">{t('common.asset')}</th>
                      <th className="py-1.5 text-end font-medium">{t('dataHealth.trust')}</th>
                      <th className="py-1.5 text-end font-medium">{t('dataHealth.calibrated')}</th>
                      <th className="py-1.5 text-start font-medium">
                        {t('dataHealth.crossValidation')}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {health.rows.map((row) => (
                      <tr key={row.code} className="border-t border-border/60 align-top">
                        <td className="py-1.5 font-mono text-text-muted">{row.code}</td>
                        <td className="py-1.5">
                          <span className="font-mono">{row.assetCode}</span>
                          <span className="ms-1 text-text-faint">{row.kind}</span>
                        </td>
                        <td
                          className={cn(
                            'py-1.5 text-end font-mono tabular-nums',
                            TRUST_TONE[row.band] ?? '',
                          )}
                        >
                          {num(row.trust)}
                          {row.adjustedTrust !== null && row.adjustedTrust !== row.trust ? (
                            <span className="ms-1 text-[10px] text-text-faint">
                              → {num(row.adjustedTrust)}
                            </span>
                          ) : null}
                        </td>
                        <td className="py-1.5 text-end font-mono tabular-nums text-text-muted">
                          {row.lastCalibratedDaysAgo === null
                            ? '—'
                            : `${row.lastCalibratedDaysAgo} ${t('dataHealth.daysAgo')}`}
                        </td>
                        <td className="py-1.5">
                          {row.verdict ? (
                            <div className="min-w-0">
                              <Badge tone={VERDICT_TONE[row.verdict] ?? 'muted'}>
                                {t(`dataHealth.verdict.${row.verdict}`)}
                              </Badge>
                              <p className="mt-0.5 text-[10px] leading-relaxed text-text-faint">
                                {locale === 'ar' ? row.verdictReasonAr : row.verdictReason}
                              </p>
                            </div>
                          ) : (
                            <span className="text-text-faint">
                              {locale === 'ar' ? row.reasonAr : row.reason}
                            </span>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </PanelBody>
        </Panel>
      </div>
    </>
  )
}
