import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { AssetPicker } from '@/components/intelligence/asset-picker'
import { CounterfactualRunner } from '@/components/intelligence/counterfactual-runner'
import {
  DemoDataBadge,
  ErrorState,
  KeyValue,
  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 { analyseAsset, pickFocusAsset } from '@/lib/services/intelligence-service'
import { buildLevers } from '@/lib/services/counterfactual-service'
import { listCounterfactualRuns } from '@/lib/services/counterfactual-service'

export const metadata: Metadata = { title: 'Counterfactual Explorer' }
export const dynamic = 'force-dynamic'

/** Counterfactual Explorer (§9, §10). */
export default async function CounterfactualPage({
  searchParams,
}: {
  searchParams: Promise<{ asset?: string }>
}) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('counterfactual.run')) return <PermissionGate />

  const { asset } = await searchParams
  const assetCode = asset?.trim() || (await pickFocusAsset())
  const intel = assetCode ? await analyseAsset(assetCode) : null

  if (!intel) {
    return (
      <>
        <PageHeader title={t('counterfactual.title')} subtitle={t('counterfactual.subtitle')} />
        <ErrorState title={t('errors.NOT_FOUND')} body={assetCode ?? ''} />
      </>
    )
  }

  const levers = buildLevers(intel)
  const history = await listCounterfactualRuns(6)

  return (
    <>
      <PageHeader
        title={t('counterfactual.title')}
        subtitle={t('counterfactual.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
        action={<AssetPicker current={intel.assetCode} />}
      />

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          label={t('common.riskScore')}
          value={formatNumber(locale, intel.focus.risk.score, { maximumFractionDigits: 0 })}
          unit="%"
          state={
            intel.focus.risk.score >= 70 ? 'critical' : intel.focus.risk.score >= 45 ? 'warning' : 'normal'
          }
          hint={intel.assetCode}
        />
        <StatCard
          label={t('preventionWindow.eventIn')}
          value={
            intel.prediction.etaMinutes === null ? '—' : formatNumber(locale, intel.prediction.etaMinutes)
          }
          unit={t('common.minutes')}
        />
        <StatCard
          label={t('counterfactual.levers')}
          value={formatNumber(locale, levers.length)}
        />
        <StatCard
          label={t('radar.backup')}
          value={formatNumber(locale, intel.resources.transferCapacityMw, { maximumFractionDigits: 1 })}
          unit="MW"
        />
      </div>

      <div className="mt-6 grid gap-4 lg:grid-cols-[1fr_20rem]">
        <CounterfactualRunner assetCode={intel.assetCode} />

        <div className="min-w-0 space-y-4">
          <Panel>
            <PanelHeader title={t('counterfactual.levers')} />
            <PanelBody className="pt-0">
              {levers.length === 0 ? (
                <p className="py-2 text-xs text-text-muted">{t('counterfactual.noLevers')}</p>
              ) : (
                <div className="space-y-1">
                  {levers.map((lever) => (
                    <KeyValue
                      key={lever.key}
                      label={lever.label(lever.maxDose)}
                      value={`${formatNumber(locale, lever.maxDose, { maximumFractionDigits: 1 })} ${lever.unit}`}
                    />
                  ))}
                </div>
              )}
            </PanelBody>
          </Panel>

          <Panel>
            <PanelHeader title={t('counterfactual.history')} />
            <PanelBody className="pt-0">
              {history.length === 0 ? (
                <p className="py-2 text-xs text-text-muted">{t('counterfactual.noHistory')}</p>
              ) : (
                <ul className="divide-y divide-border/60">
                  {history.map((run) => (
                    <li key={run.code} className="py-2">
                      <p className="font-mono text-[11px] text-text">{run.assetCode}</p>
                      <p className="mt-0.5 text-[11px] leading-relaxed text-text-muted">
                        {locale === 'ar' ? run.summaryAr : run.summary}
                      </p>
                    </li>
                  ))}
                </ul>
              )}
            </PanelBody>
          </Panel>
        </div>
      </div>
    </>
  )
}
