import type { Metadata } from 'next'

import { DnaExplorer, type DnaPatternView, type DnaCurrentMatch } from '@/components/console/dna-explorer'
import { PermissionGate } from '@/components/console/permission-gate'
import { DemoDataBadge, PageHeader, Panel, PanelBody, PanelHeader, StatCard } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { REGIONS } from '@/lib/data/regions'
import { DNA_FEATURES, matchDna } from '@/lib/engine/dna'
import { environmentFor, extractAssetDna } from '@/lib/engine/grid'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { getGridSnapshot, loadDnaPatterns } from '@/lib/services/grid-service'

export const metadata: Metadata = { title: 'Failure DNA' }
export const dynamic = 'force-dynamic'

export default async function FailureDnaPage({
  searchParams,
}: {
  searchParams: Promise<{ focus?: string }>
}) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()

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

  const [{ focus }, patterns, records, snapshot] = await Promise.all([
    searchParams,
    loadDnaPatterns(),
    prisma.failurePattern.findMany({
      include: { dna: true, region: { select: { code: true, name: true, nameAr: true } } },
      orderBy: { occurredAt: 'desc' },
    }),
    getGridSnapshot(),
  ])

  const views: DnaPatternView[] = records
    .filter((record) => record.dna)
    .map((record) => ({
      code: record.dna!.code,
      patternCode: record.code,
      name: record.name,
      nameAr: record.nameAr,
      description: record.description,
      descriptionAr: record.descriptionAr,
      eventType: record.eventType,
      severity: record.severity,
      occurredAt: record.occurredAt.getTime(),
      regionName: record.region?.name ?? null,
      regionNameAr: record.region?.nameAr ?? null,
      assetTypeKey: record.assetTypeKey,
      durationMin: record.durationMin,
      customersAffect: record.customersAffect,
      energyLostMwh: record.energyLostMwh,
      outcome: record.outcome,
      outcomeAr: record.outcomeAr,
      vector: Object.fromEntries(
        DNA_FEATURES.map((feature) => [feature, record.dna![feature] as number]),
      ) as Record<string, number>,
    }))

  // Live matches: what the riskiest assets currently resemble.
  const candidates = [...snapshot.assets].sort((a, b) => b.risk.score - a.risk.score).slice(0, 10)

  const currentMatches: DnaCurrentMatch[] = candidates.map((candidate) => {
    const region = REGIONS.find((entry) => entry.code === candidate.profile.regionCode)!
    const envAt = environmentFor(region, {})
    const regionSnapshot = snapshot.regions.find((entry) => entry.code === region.code)
    const vector = extractAssetDna({
      profile: candidate.profile,
      ts: snapshot.ts,
      sample: candidate.sample,
      env: envAt(snapshot.ts),
      envAt,
      perturbation: {},
      neighbourStress: candidate.neighbourStress,
      renewableVariabilityPct: regionSnapshot?.renewableVariabilityPct ?? 0,
    })
    const [top] = matchDna(vector, patterns, 1)

    return {
      assetCode: candidate.profile.code,
      regionCode: candidate.profile.regionCode,
      riskScore: candidate.risk.score,
      similarity: top?.similarity ?? 0,
      dnaCode: top?.pattern.code ?? null,
      vector: vector as unknown as Record<string, number>,
    }
  })

  const strongest = currentMatches.reduce(
    (max, match) => (match.similarity > max ? match.similarity : max),
    0,
  )

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

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard label={t('dna.library')} value={formatNumber(locale, views.length)} />
        <StatCard label={t('dna.dimensions')} value={formatNumber(locale, DNA_FEATURES.length)} />
        <StatCard
          label={t('dna.topMatches')}
          value={formatNumber(locale, strongest, { maximumFractionDigits: 0 })}
          unit="%"
          state={strongest >= 75 ? 'critical' : strongest >= 55 ? 'warning' : 'normal'}
        />
        <StatCard
          label={t('dna.matches')}
          value={formatNumber(locale, currentMatches.filter((match) => match.similarity >= 60).length)}
        />
      </div>

      <Panel className="mt-6">
        <PanelHeader title={t('dna.howItWorks')} subtitle={t('dna.howItWorksBody')} />
        <PanelBody className="pt-0">
          <DnaExplorer patterns={views} matches={currentMatches} focus={focus} />
        </PanelBody>
      </Panel>
    </>
  )
}
