import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { AssetPicker } from '@/components/intelligence/asset-picker'
import { ParetoExplorer } from '@/components/intelligence/pareto-explorer'
import { StrategyTable } from '@/components/intelligence/strategy-table'
import { FutureBranches } from '@/components/intelligence/future-branches'
import { ConfidencePanel } from '@/components/intelligence/confidence-panel'
import {
  DemoDataBadge,
  ErrorState,
  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, futureBranches, pickFocusAsset } from '@/lib/services/intelligence-service'
import { matchPreventionPatterns } from '@/lib/services/optimization-service'
import { exploreStrategies } from '@/lib/services/pareto-service'

export const metadata: Metadata = { title: 'Self-Healing Lab' }
export const dynamic = 'force-dynamic'

/** Self-Healing Lab (§12) — candidate strategies, measured and ranked. */
export default async function SelfHealingPage({
  searchParams,
}: {
  searchParams: Promise<{ asset?: string; objective?: string }>
}) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('optimization.run')) return <PermissionGate />

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

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

  const [branches, patterns, pareto] = await Promise.all([
    futureBranches(intel),
    matchPreventionPatterns({
      eventType: intel.prediction.eventType,
      assetTypeKey: intel.focus.profile.assetTypeKey,
      loadPct: intel.focus.sample.loadPct,
      tempC: intel.focus.sample.tempC,
      dnaSimilarity: intel.focus.dnaSimilarity,
    }),
    // Server-rendered so the frontier is on screen with the ranking rather than a
    // click behind it — the comparison is the point, not a secondary view of it.
    exploreStrategies({ assetCode: intel.assetCode }),
  ])

  const best = intel.optimisation.best

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

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          label={t('selfHealing.strategy')}
          value={formatNumber(locale, intel.optimisation.strategies.length)}
          hint={t(`selfHealing.objectiveKey.${intel.optimisation.objectiveKey}`)}
        />
        <StatCard
          label={t('selfHealing.riskAfter')}
          value={best ? formatNumber(locale, best.evaluation.riskAfter, { maximumFractionDigits: 0 }) : '—'}
          unit="%"
          state={best && best.evaluation.riskAfter < 25 ? 'normal' : 'warning'}
          hint={
            best
              ? `${formatNumber(locale, best.evaluation.riskBefore, { maximumFractionDigits: 0 })}% → ${formatNumber(locale, best.evaluation.riskAfter, { maximumFractionDigits: 0 })}%`
              : undefined
          }
        />
        <StatCard
          label={t('selfHealing.cost')}
          value={best ? formatNumber(locale, best.costSar) : '—'}
          unit={t('common.sar')}
        />
        <StatCard
          label={t('selfHealing.executionTime')}
          value={best ? formatNumber(locale, best.executionMin) : '—'}
          unit={t('common.minutes')}
        />
      </div>

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

        <div className="min-w-0 space-y-4">
          <ConfidencePanel confidence={intel.orchestration.confidence} />

          <Panel>
            <PanelHeader title={t('warRoom.patterns')} />
            <PanelBody className="pt-0">
              {patterns.length === 0 ? (
                <p className="py-2 text-xs text-text-muted">{t('warRoom.noPatterns')}</p>
              ) : (
                <ul className="divide-y divide-border/60">
                  {patterns.map((match) => (
                    <li key={match.pattern.code} className="py-2">
                      <div className="flex items-baseline justify-between gap-2">
                        <p className="font-mono text-[11px] text-text">{match.pattern.code}</p>
                        <p className="tnum text-[11px] text-brand">
                          {formatNumber(locale, match.similarity, { maximumFractionDigits: 0 })}%
                        </p>
                      </div>
                      <p className="mt-0.5 text-[11px] text-text-muted">
                        {locale === 'ar' ? match.pattern.strategyLabelAr : match.pattern.strategyLabel}
                      </p>
                      <p className="tnum mt-0.5 text-[10px] text-text-faint">
                        {t('warRoom.patternSuccess')}{' '}
                        {formatNumber(locale, match.pattern.riskBefore, { maximumFractionDigits: 0 })}% →{' '}
                        {formatNumber(locale, match.pattern.riskAfter, { maximumFractionDigits: 0 })}%
                      </p>
                    </li>
                  ))}
                </ul>
              )}
            </PanelBody>
          </Panel>
        </div>
      </div>

      {/* 4.0: the same strategies read as a trade-off space rather than a ranking, with
          a stated reason for every option that is not the recommendation (§35, §37). */}
      <div className="mt-6">
        <ParetoExplorer
          assetCode={intel.assetCode}
          initial={pareto}
          canRun={user.permissions.has('optimization.run')}
        />
      </div>

      <FutureBranches branches={branches} horizonMin={intel.prediction.horizonMin} className="mt-6" />
    </>
  )
}
