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

import { AssetRiskTrajectory, AssetTrendChart } from '@/components/console/asset-charts'
import { PermissionGate } from '@/components/console/permission-gate'
import { DnaMatchPanel } from '@/components/panels/dna-match'
import { RecommendationsPanel } from '@/components/panels/recommendations-panel'
import { RiskExplanation } from '@/components/panels/risk-explanation'
import { AssetTimeline } from '@/components/panels/asset-timeline'
import { RiskGauge } from '@/components/charts/risk-gauge'
import {
  Badge,
  DemoDataBadge,
  EmptyState,
  KeyValue,
  Meter,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StatCard,
  StateBadge,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { healthToBand } from '@/lib/domain/enums'
import { describePrediction } from '@/lib/engine/explain'
import { getI18n, localised } from '@/lib/i18n/server'
import { formatDate, formatNumber } from '@/lib/i18n/translate'
import { assetForwardSeries, getAssetDetail } from '@/lib/services/asset-service'
import { styleForHealth, 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) }
}

export default async function AssetPage({ params }: { params: Promise<{ code: string }> }) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()

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

  const { code } = await params
  const detail = await getAssetDetail(decodeURIComponent(code))
  if (!detail) notFound()

  const { record, live, prediction, dnaMatches, actions, history, rulDays } = detail
  const forward = assetForwardSeries(prediction)
  const healthBand = healthToBand(live.sample.effectiveHealth)

  const narrative = describePrediction(
    {
      profile: live.profile,
      sample: live.sample,
      risk: live.risk,
      dnaSimilarity: live.dnaSimilarity,
      etaMinutes: prediction.etaMinutes,
      confidence: prediction.confidence,
    },
    locale,
  )

  // Map the live candidate actions onto their persisted rows so approvals survive a
  // reload rather than living only in component state.
  const storedByType = new Map(
    record.recommendations.map((recommendation) => [recommendation.actionType, recommendation]),
  )
  const recommendationActions = actions.map((action) => {
    const stored = storedByType.get(action.actionType)
    return {
      ...action,
      recordId: stored?.id,
      status: stored?.status,
    }
  })

  return (
    <>
      <PageHeader
        title={`${record.code} · ${localised(record, 'name', locale)}`}
        subtitle={`${t(`assetType.${record.assetType.key}`)} · ${localised(record.region, 'name', locale)} · ${localised(record.site, 'name', locale)}`}
        badge={
          <div className="flex flex-wrap items-center gap-2">
            <StateBadge
              state={live.state}
              label={t(`states.${live.state}`)}
              pulse={live.risk.score >= 75}
            />
            <Badge tone="muted">{t(`assetStatus.${record.status}`)}</Badge>
            <DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />
          </div>
        }
        action={
          <Link href="/assets" className="text-xs font-medium text-brand hover:underline">
            ← {t('assets.backToList')}
          </Link>
        }
      />

      {/* ── Condition summary ─────────────────────────────────────────────── */}
      <div className="grid gap-6 xl:grid-cols-[280px_1fr]">
        <Panel className="flex flex-col items-center justify-center p-6">
          <RiskGauge
            value={live.risk.score}
            label={t('common.riskScore')}
            sublabel={
              prediction.etaMinutes !== null
                ? `${t('predictions.columns.eta')}: ${prediction.etaMinutes} ${t('common.units.minutes')}`
                : t('predictions.etaNone')
            }
          />
          <div className="mt-5 w-full space-y-3 border-t border-border pt-5">
            <div>
              <div className="mb-1.5 flex items-baseline justify-between">
                <span className="text-xs text-text-muted">{t('assets.passport.currentHealth')}</span>
                <span className={`tnum text-sm font-medium ${styleForHealth(live.sample.effectiveHealth).text}`}>
                  {formatNumber(locale, live.sample.effectiveHealth, { maximumFractionDigits: 0 })}
                </span>
              </div>
              <Meter value={live.sample.effectiveHealth} state={live.state} />
              <p className="mt-1 text-[11px] text-text-faint">{t(`healthBand.${healthBand}`)}</p>
            </div>
            <KeyValue
              label={t('assets.passport.rul')}
              value={`${formatNumber(locale, rulDays)} ${t('common.units.days')}`}
              mono
            />
            <KeyValue
              label={t('common.confidence')}
              value={`${formatNumber(locale, prediction.confidence * 100, { maximumFractionDigits: 0 })}%`}
              mono
            />
          </div>
        </Panel>

        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          <StatCard
            label={t('assets.columns.load')}
            value={formatNumber(locale, live.sample.loadPct, { maximumFractionDigits: 1 })}
            unit="%"
            hint={`${formatNumber(locale, live.sample.loadMw, { maximumFractionDigits: 1 })} / ${formatNumber(locale, record.capacityMw)} ${t('common.units.mw')}`}
            state={live.sample.loadPct >= 90 ? 'critical' : live.sample.loadPct >= 75 ? 'warning' : 'normal'}
          />
          <StatCard
            label={t('assets.columns.temperature')}
            value={formatNumber(locale, live.sample.tempC, { maximumFractionDigits: 1 })}
            unit={t('common.units.celsius')}
            hint={`${t('assets.passport.ratedTemp')} ${formatNumber(locale, record.ratedTempC)} · ${t('assets.passport.coolingType')} ${record.coolingType}`}
            state={
              live.sample.tempC >= record.ratedTempC
                ? 'critical'
                : live.sample.tempC >= record.ratedTempC - 15
                  ? 'warning'
                  : 'normal'
            }
          />
          <StatCard
            label={t('grid.electrical.voltage')}
            value={formatNumber(locale, live.sample.voltageKv, { maximumFractionDigits: 2 })}
            unit={t('common.units.kv')}
            hint={`${formatNumber(locale, live.sample.voltageDeviationPct, { maximumFractionDigits: 2 })}% ${t('grid.stability.voltage')}`}
          />
          <StatCard
            label={t('grid.electrical.current')}
            value={formatNumber(locale, live.sample.currentA, { maximumFractionDigits: 0 })}
            unit={t('common.units.ampere')}
          />
          <StatCard
            label={t('grid.electrical.powerFactor')}
            value={formatNumber(locale, live.sample.powerFactor, {
              minimumFractionDigits: 3,
              maximumFractionDigits: 3,
            })}
            hint={`${formatNumber(locale, live.sample.reactivePowerMvar, { maximumFractionDigits: 1 })} ${t('common.units.mvar')}`}
          />
          <StatCard
            label={t('grid.electrical.thd')}
            value={formatNumber(locale, live.sample.thdPct, { maximumFractionDigits: 2 })}
            unit="%"
            hint={`${t('assets.passport.customers')}: ${formatNumber(locale, record.customersServed)}`}
          />
        </div>
      </div>

      {/* ── Trend and projection ──────────────────────────────────────────── */}
      <Panel className="mt-6">
        <PanelHeader
          title={t('assets.passport.history')}
          subtitle={t('timeMachine.note')}
        />
        <PanelBody>
          {history.length === 0 ? (
            <EmptyState title={t('common.noData')} />
          ) : (
            <AssetTrendChart
              history={history}
              forward={forward}
              ratedTempC={record.ratedTempC}
              nowTs={live.sample.ts}
            />
          )}
        </PanelBody>
      </Panel>

      {/* ── Explanation and DNA ───────────────────────────────────────────── */}
      <div className="mt-6 grid gap-6 xl:grid-cols-2">
        <RiskExplanation
          risk={live.risk}
          narrative={narrative}
          modelVersion={record.predictions[0]?.modelVersion?.version}
        />
        <DnaMatchPanel matches={dnaMatches} />
      </div>

      {/* ── Risk trajectory ───────────────────────────────────────────────── */}
      <Panel className="mt-6">
        <PanelHeader
          title={t('assets.passport.riskForecast')}
          subtitle={
            prediction.etaMinutes !== null
              ? t('predictions.breachReason.' + (prediction.breachReason ?? 'risk'))
              : t('timeMachine.noBreach')
          }
          action={
            <Badge tone={prediction.etaMinutes !== null ? 'brand' : 'muted'}>
              {t('predictions.horizon')}: {prediction.horizonMin} {t('common.units.minutes')}
            </Badge>
          }
        />
        <PanelBody>
          <AssetRiskTrajectory forward={forward} />
        </PanelBody>
      </Panel>

      {/* ── Recommendations ───────────────────────────────────────────────── */}
      {user.permissions.has('recommendations.read') ? (
        <RecommendationsPanel
          className="mt-6"
          assetCode={record.code}
          actions={recommendationActions}
          etaMinutes={prediction.etaMinutes}
          canSimulate={user.permissions.has('simulations.run')}
          canApprove={user.permissions.has('recommendations.approve')}
          canExecute={user.permissions.has('recommendations.execute')}
        />
      ) : null}

      {/* ── Passport detail ───────────────────────────────────────────────── */}
      <div className="mt-6 grid gap-6 lg:grid-cols-2">
        <Panel>
          <PanelHeader title={t('assets.passport.basic')} />
          <PanelBody>
            <dl className="divide-y divide-border/60">
              <KeyValue label={t('assets.passport.manufacturer')} value={record.manufacturer} />
              <KeyValue label={t('assets.passport.model')} value={record.model} />
              <KeyValue label={t('assets.passport.serial')} value={record.serialNumber} mono />
              <KeyValue
                label={t('assets.passport.installed')}
                value={formatDate(locale, record.installedAt)}
              />
              <KeyValue
                label={t('assets.passport.age')}
                value={`${formatNumber(locale, live.ageYears, { maximumFractionDigits: 1 })} ${t('common.units.years')}`}
              />
              <KeyValue
                label={t('assets.passport.voltage')}
                value={`${formatNumber(locale, record.voltageKv)} ${t('common.units.kv')}`}
              />
              <KeyValue
                label={t('common.capacity')}
                value={`${formatNumber(locale, record.capacityMw)} ${t('common.units.mw')}`}
              />
              <KeyValue label={t('assets.passport.site')} value={localised(record.site, 'name', locale)} />
              {record.parent ? (
                <KeyValue
                  label={t('assets.passport.parent')}
                  value={
                    <Link
                      href={`/assets/${encodeURIComponent(record.parent.code)}`}
                      className="text-brand hover:underline"
                    >
                      {record.parent.code}
                    </Link>
                  }
                />
              ) : null}
              <KeyValue
                label={t('assets.passport.lastMaintenance')}
                value={
                  record.lastMaintenanceAt ? formatDate(locale, record.lastMaintenanceAt) : t('common.none')
                }
              />
              <KeyValue
                label={t('assets.passport.nextMaintenance')}
                value={
                  record.nextMaintenanceAt ? formatDate(locale, record.nextMaintenanceAt) : t('common.none')
                }
              />
              <KeyValue
                label={t('assets.columns.criticality')}
                value={t(`severity.${record.criticality}`)}
              />
            </dl>
          </PanelBody>
        </Panel>

        <div className="space-y-6">
          <Panel>
            <PanelHeader
              title={t('assets.passport.sensors')}
              action={<Badge tone="muted">{record.sensors.length}</Badge>}
            />
            <PanelBody>
              <ul className="space-y-1.5">
                {record.sensors.map((sensor) => (
                  <li
                    key={sensor.id}
                    className="flex items-center justify-between gap-3 rounded-lg border border-border bg-surface-2/40 px-3 py-2"
                  >
                    <div className="min-w-0">
                      <p className="truncate font-mono text-[11px] text-text-muted">{sensor.code}</p>
                      <p className="text-xs text-text">{sensor.kind}</p>
                    </div>
                    <Badge
                      tone={
                        sensor.status === 'healthy'
                          ? 'brand'
                          : sensor.status === 'degraded'
                            ? 'info'
                            : 'neutral'
                      }
                    >
                      {sensor.status}
                    </Badge>
                  </li>
                ))}
              </ul>
            </PanelBody>
          </Panel>

          <Panel>
            <PanelHeader title={t('assets.passport.documents')} />
            <PanelBody>
              <p className="text-xs leading-relaxed text-text-muted">
                {t('assets.passport.documentsNote')}
              </p>
            </PanelBody>
          </Panel>
        </div>
      </div>

      {/* ── Maintenance and incidents ─────────────────────────────────────── */}
      <div className="mt-6 grid gap-6 lg:grid-cols-2">
        <Panel>
          <PanelHeader title={t('assets.passport.maintenance')} />
          {record.maintenance.length === 0 ? (
            <EmptyState title={t('assets.passport.noMaintenance')} />
          ) : (
            <ul className="divide-y divide-border">
              {record.maintenance.map((entry) => (
                <li key={entry.id} className="px-4 py-3 sm:px-5">
                  <div className="flex flex-wrap items-center justify-between gap-2">
                    <div className="flex flex-wrap items-center gap-2">
                      <Badge tone="neutral">{t(`maintenance.kind.${entry.kind}`)}</Badge>
                      <span className="font-mono text-[11px] text-text-faint">{entry.code}</span>
                    </div>
                    <span className="text-[11px] text-text-muted">
                      {entry.performedAt
                        ? formatDate(locale, entry.performedAt)
                        : formatDate(locale, entry.scheduledAt)}
                    </span>
                  </div>
                  <p className="mt-1.5 text-xs leading-relaxed text-text-muted">
                    {localised(entry, 'findings', locale)}
                  </p>
                  {entry.healthAfter > entry.healthBefore ? (
                    <p className="tnum mt-1 text-[11px] text-brand">
                      {t('maintenance.healthChange', {
                        before: formatNumber(locale, entry.healthBefore, { maximumFractionDigits: 0 }),
                        after: formatNumber(locale, entry.healthAfter, { maximumFractionDigits: 0 }),
                      })}
                    </p>
                  ) : null}
                </li>
              ))}
            </ul>
          )}
        </Panel>

        <Panel>
          <PanelHeader title={t('assets.passport.failures')} />
          {record.incidents.length === 0 ? (
            <EmptyState title={t('assets.passport.noIncidents')} />
          ) : (
            <ul className="divide-y divide-border">
              {record.incidents.map((incident) => (
                <li key={incident.id}>
                  <Link
                    href={`/incidents/${incident.code}`}
                    className="block px-4 py-3 transition-colors hover:bg-surface-2/50 sm:px-5"
                  >
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <span className="font-mono text-[11px] text-brand">{incident.code}</span>
                      <span className="text-[11px] text-text-muted">
                        {formatDate(locale, incident.startedAt)}
                      </span>
                    </div>
                    <p className="mt-1.5 text-sm text-text">{localised(incident, 'title', locale)}</p>
                    <p className="mt-1 text-[11px] text-text-faint">
                      {t(`severity.${incident.severity}`)} ·{' '}
                      {incident.wasPrevented
                        ? t('incidents.wasPrevented')
                        : `${formatNumber(locale, incident.customersAffected)} ${t('common.units.customers')}`}
                    </p>
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </Panel>
      </div>

      {/* ── Chronological record ──────────────────────────────────────────── */}
      <AssetTimeline
        className="mt-6"
        source={{
          installedAt: record.installedAt,
          maintenance: record.maintenance,
          incidents: record.incidents,
          predictions: record.predictions,
          alerts: record.alerts,
        }}
      />

      {/* ── Recorded predictions ──────────────────────────────────────────── */}
      {record.predictions.length > 0 ? (
        <Panel className="mt-6">
          <PanelHeader title={t('predictions.title')} />
          <ul className="divide-y divide-border">
            {record.predictions.map((entry) => (
              <li key={entry.id} className="flex flex-wrap items-center gap-4 px-4 py-3 sm:px-5">
                <span className="font-mono text-[11px] text-brand">{entry.code}</span>
                <span className="text-sm text-text">{t(`eventType.${entry.eventType}`)}</span>
                <Badge tone="muted">{t(`predictions.status.${entry.status}`)}</Badge>
                <span className="tnum ms-auto text-sm">
                  <span className={styleForRisk(entry.riskScore).text}>
                    {formatNumber(locale, entry.riskScore, { maximumFractionDigits: 0 })}%
                  </span>
                  <span className="ms-3 text-text-faint">
                    {formatNumber(locale, entry.probability * 100, { maximumFractionDigits: 0 })}%{' '}
                    {t('common.probability').toLowerCase()}
                  </span>
                </span>
              </li>
            ))}
          </ul>
        </Panel>
      ) : null}
    </>
  )
}
