import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { AssetPicker } from '@/components/intelligence/asset-picker'
import { CascadeTimeline } from '@/components/intelligence/cascade-timeline'
import { CascadeTree } from '@/components/intelligence/cascade-tree'
import { FutureBranches } from '@/components/intelligence/future-branches'
import {
  DemoDataBadge,
  ErrorState,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { formatDateTime } from '@/lib/i18n/translate'
import { analyseAsset, futureBranches, pickFocusAsset } from '@/lib/services/intelligence-service'
import { listCascadeRuns } from '@/lib/services/cascade-service'

export const metadata: Metadata = { title: 'Domino View' }
export const dynamic = 'force-dynamic'

/** Domino View (§5, §6) with the three futures beneath it (§8). */
export default async function CascadePage({
  searchParams,
}: {
  searchParams: Promise<{ asset?: string }>
}) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('simulations.read')) 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('cascade.title')} subtitle={t('cascade.subtitle')} />
        <ErrorState title={t('errors.NOT_FOUND')} body={assetCode ?? ''} />
      </>
    )
  }

  const [branches, history] = await Promise.all([futureBranches(intel), listCascadeRuns(8)])

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

      <CascadeTimeline result={intel.cascade} />

      {/* 4.0: the same walk as a branching tree, plus the cheapest place to cut it. The
          timeline answers "what happens in what order"; this answers "which branch, and
          where do I stop it" (§43, §45). */}
      <div className="mt-6">
        <CascadeTree
          tree={intel.cascadeTree}
          breakpoints={intel.breakpoints}
          contained={intel.cascade.affectedAssets <= 1}
        />
      </div>

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

      <Panel className="mt-6">
        <PanelHeader title={t('cascade.history')} />
        <PanelBody className="pt-0">
          {history.length === 0 ? (
            <p className="py-3 text-xs text-text-muted">{t('cascade.noHistory')}</p>
          ) : (
            <ul className="divide-y divide-border/60">
              {history.map((run) => (
                <li key={run.code} className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 py-2.5">
                  <div className="min-w-0">
                    <p className="font-mono text-xs text-text">{run.originCode}</p>
                    <p className="mt-0.5 text-[11px] leading-relaxed text-text-muted">
                      {locale === 'ar' ? run.summaryAr : run.summary}
                    </p>
                  </div>
                  <p className="tnum text-[10px] text-text-faint">{formatDateTime(locale, run.ts.getTime())}</p>
                </li>
              ))}
            </ul>
          )}
        </PanelBody>
      </Panel>
    </>
  )
}
