import type { Metadata } from 'next'
import Link from 'next/link'
import { notFound } from 'next/navigation'

import { PermissionGate } from '@/components/console/permission-gate'
import { RiskGauge } from '@/components/charts/risk-gauge'
import {
  Badge,
  DemoDataBadge,
  EmptyState,
  KeyValue,
  Meter,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StateBadge,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { riskToState } from '@/lib/domain/enums'
import { getI18n, localised } from '@/lib/i18n/server'
import { formatDateTime, formatNumber } from '@/lib/i18n/translate'
import { styleForRisk } from '@/lib/ui/state-styles'

export const dynamic = 'force-dynamic'

export async function generateMetadata({
  params,
}: {
  params: Promise<{ code: string }>
}): Promise<Metadata> {
  const { code } = await params
  return { title: decodeURIComponent(code) }
}

/**
 * A single recorded prediction.
 *
 * This page shows the prediction *as it was raised* — the factor breakdown, explanation
 * and recommendations that were stored at the time. The asset page shows the same asset
 * as it is now. Keeping the two distinct is what makes the record auditable: a
 * prediction that has been superseded should not silently rewrite itself.
 */
export default async function PredictionPage({ params }: { params: Promise<{ code: string }> }) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()

  if (!user?.permissions.has('predictions.read')) return <PermissionGate />

  const { code } = await params
  const prediction = await prisma.prediction.findUnique({
    where: { code: decodeURIComponent(code) },
    include: {
      asset: {
        select: {
          code: true,
          name: true,
          nameAr: true,
          capacityMw: true,
          region: { select: { name: true, nameAr: true } },
          assetType: { select: { key: true } },
        },
      },
      factors: { orderBy: { contribution: 'desc' } },
      recommendations: { orderBy: { priority: 'asc' } },
      modelVersion: true,
      alerts: { select: { code: true, level: true, status: true } },
    },
  })

  if (!prediction) notFound()

  const maxContribution = Math.max(...prediction.factors.map((factor) => factor.contribution), 1)
  const state = riskToState(prediction.riskScore)

  return (
    <>
      <PageHeader
        title={`${prediction.code} · ${t(`eventType.${prediction.eventType}`)}`}
        subtitle={`${prediction.asset.code} · ${localised(prediction.asset.region, 'name', locale)} · ${t(`assetType.${prediction.asset.assetType.key}`)}`}
        badge={
          <div className="flex flex-wrap items-center gap-2">
            <StateBadge state={state} label={t(`states.${state}`)} />
            <Badge tone={prediction.status === 'prevented' ? 'brand' : 'muted'}>
              {t(`predictions.status.${prediction.status}`)}
            </Badge>
            <DemoDataBadge label={t('common.simulated')} />
          </div>
        }
        action={
          <Link href="/predictions" className="text-xs font-medium text-brand hover:underline">
            ← {t('predictions.title')}
          </Link>
        }
      />

      <div className="grid gap-6 xl:grid-cols-[280px_1fr]">
        <Panel className="flex flex-col items-center p-6">
          <RiskGauge value={prediction.riskScore} label={t('common.riskScore')} />
          <dl className="mt-5 w-full space-y-1 border-t border-border pt-5">
            <KeyValue
              label={t('common.probability')}
              value={`${formatNumber(locale, prediction.probability * 100, { maximumFractionDigits: 0 })}%`}
              mono
            />
            <KeyValue
              label={t('common.confidence')}
              value={`${formatNumber(locale, prediction.confidence * 100, { maximumFractionDigits: 0 })}%`}
              mono
            />
            <KeyValue label={t('common.severity')} value={t(`severity.${prediction.severity}`)} />
            <KeyValue
              label={t('predictions.columns.eta')}
              value={`${formatNumber(locale, prediction.etaMinutes)} ${t('common.units.minutes')}`}
              mono
            />
            <KeyValue
              label={t('common.timestamp')}
              value={formatDateTime(locale, prediction.etaAt)}
            />
            <KeyValue
              label={t('predictions.explain.modelVersion')}
              value={`${prediction.modelVersion.key} ${prediction.modelVersion.version}`}
              mono
            />
          </dl>
        </Panel>

        <div className="space-y-6">
          <Panel>
            <PanelHeader
              title={t('predictions.explain.title')}
              subtitle={t('predictions.explain.subtitle')}
            />
            <PanelBody>
              {prediction.factors.length === 0 ? (
                <p className="text-sm text-text-muted">{t('predictions.explain.noFactors')}</p>
              ) : (
                <ul className="space-y-4">
                  {prediction.factors.map((factor) => (
                    <li key={factor.id}>
                      <div className="flex flex-wrap items-baseline justify-between gap-2">
                        <span className="text-sm font-medium text-text">
                          {localised(factor, 'label', 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">
                        {localised(factor, 'detail', locale)}{' '}
                        <span className="tnum text-text-faint">
                          ({formatNumber(locale, factor.value, { 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">
                  {localised(prediction, 'explanation', locale)}
                </p>
              </div>
            </PanelBody>
          </Panel>

          {prediction.dnaCode ? (
            <Panel>
              <PanelHeader title={t('dna.topMatches')} />
              <PanelBody>
                <div className="flex flex-wrap items-center justify-between gap-3">
                  <Link
                    href={`/failure-dna?focus=${prediction.dnaCode}`}
                    className="font-mono text-sm text-brand hover:underline"
                  >
                    {prediction.dnaCode}
                  </Link>
                  <span className={`tnum text-2xl font-semibold ${styleForRisk(prediction.dnaSimilarity).text}`}>
                    {formatNumber(locale, prediction.dnaSimilarity, { maximumFractionDigits: 0 })}%
                  </span>
                </div>
                <Meter
                  value={prediction.dnaSimilarity}
                  state={riskToState(prediction.dnaSimilarity)}
                  className="mt-3"
                />
              </PanelBody>
            </Panel>
          ) : null}
        </div>
      </div>

      <Panel className="mt-6">
        <PanelHeader
          title={t('recommendations.title')}
          subtitle={t('recommendations.subtitle')}
          action={
            <Link
              href={`/assets/${encodeURIComponent(prediction.asset.code)}`}
              className="text-xs font-medium text-brand hover:underline"
            >
              {t('commandCenter.openAsset')}
            </Link>
          }
        />
        {prediction.recommendations.length === 0 ? (
          <EmptyState title={t('recommendations.empty')} />
        ) : (
          <ul className="divide-y divide-border">
            {prediction.recommendations.map((recommendation) => (
              <li key={recommendation.id} className="flex flex-wrap items-center gap-4 px-4 py-3.5 sm:px-5">
                <div className="min-w-0 flex-1">
                  <div className="flex flex-wrap items-center gap-2">
                    <Badge tone="neutral">{t(`actionType.${recommendation.actionType}`)}</Badge>
                    <Badge tone={recommendation.status === 'executed' ? 'brand' : 'muted'}>
                      {t(`recommendationStatus.${recommendation.status}`)}
                    </Badge>
                  </div>
                  <p className="mt-1.5 text-sm text-text">
                    {localised(recommendation, 'title', locale)}
                  </p>
                  <p className="mt-1 text-xs leading-relaxed text-text-muted">
                    {localised(recommendation, 'description', locale)}
                  </p>
                </div>
                <div className="text-end">
                  <p className="text-[10px] uppercase tracking-wide text-text-faint">
                    {t('recommendations.expectedReduction')}
                  </p>
                  <p className="tnum text-xl font-semibold text-brand">
                    −{formatNumber(locale, recommendation.riskReduction, { maximumFractionDigits: 1 })}
                  </p>
                </div>
              </li>
            ))}
          </ul>
        )}
      </Panel>

      {prediction.alerts.length > 0 ? (
        <Panel className="mt-6">
          <PanelHeader title={t('alerts.title')} />
          <ul className="divide-y divide-border">
            {prediction.alerts.map((alert) => (
              <li key={alert.code} className="flex items-center gap-3 px-4 py-3 sm:px-5">
                <Link href={`/alerts?focus=${alert.code}`} className="font-mono text-xs text-brand hover:underline">
                  {alert.code}
                </Link>
                <Badge tone="muted">{t(`alertLevel.${alert.level}`)}</Badge>
                <Badge tone="muted">{t(`alertStatus.${alert.status}`)}</Badge>
              </li>
            ))}
          </ul>
        </Panel>
      ) : null}
    </>
  )
}
