import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { TimeMachine } from '@/components/console/time-machine'
import { DemoDataBadge, EmptyState, PageHeader, Panel } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { getGridSnapshot } from '@/lib/services/grid-service'
import { getTimeMachine } from '@/lib/services/time-machine-service'

export const metadata: Metadata = { title: 'Energy Time Machine' }
export const dynamic = 'force-dynamic'

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

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

  const [{ asset }, snapshot] = await Promise.all([searchParams, getGridSnapshot()])

  // Default to the asset that most needs looking at, so the page opens on something
  // worth seeing rather than an arbitrary first row.
  const candidates = [...snapshot.assets]
    .sort((a, b) => b.risk.score - a.risk.score)
    .slice(0, 20)
    .map((entry) => ({
      code: entry.profile.code,
      name: entry.profile.code,
      nameAr: entry.profile.code,
      risk: entry.risk.score,
    }))

  const selected = asset && candidates.some((c) => c.code === asset) ? asset : candidates[0]?.code

  if (!selected) {
    return (
      <>
        <PageHeader title={t('timeMachine.title')} subtitle={t('timeMachine.subtitle')} />
        <Panel>
          <EmptyState title={t('common.noData')} />
        </Panel>
      </>
    )
  }

  const result = await getTimeMachine(selected)

  return (
    <>
      <PageHeader
        title={t('timeMachine.title')}
        subtitle={t('timeMachine.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
      />
      {result ? (
        <TimeMachine result={result} assets={candidates} />
      ) : (
        <Panel>
          <EmptyState title={t('assets.notFound')} />
        </Panel>
      )}
    </>
  )
}
