import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { LiveGridConsole } from '@/components/live-grid/live-grid-console'
import { Notice } from '@/components/ui/controls'
import { DemoDataBadge, ErrorState, PageHeader } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { buildInitialGrid } from '@/lib/services/live-grid-service'

export const metadata: Metadata = { title: 'Live 3D Grid' }
export const dynamic = 'force-dynamic'

/**
 * NABDH LIVE 3D GRID (4.2).
 *
 * The first state is rendered on the server so the scene has real numbers on it before any
 * JavaScript runs. A command centre that spends two seconds on a spinner has already lost
 * the argument that it is a live view of something.
 */
export default async function LiveGridPage({
  searchParams,
}: {
  searchParams: Promise<{ twin?: string; asset?: string }>
}) {
  const user = await getCurrentUser()
  const { t } = await getI18n()
  if (!user?.permissions.has('twin.read')) return <PermissionGate />

  const { twin, asset } = await searchParams
  const initial = await buildInitialGrid({
    twinCode: twin,
    focusAsset: asset,
    canSimulate: user.permissions.has('twin.simulate'),
  })

  if (!initial) {
    return (
      <>
        <PageHeader title={t('liveGrid.title')} subtitle={t('liveGrid.subtitle')} />
        <ErrorState title={t('uiState.empty')} body={t('liveGrid.subtitle')} />
      </>
    )
  }

  return (
    <>
      <PageHeader
        title={t('liveGrid.title')}
        subtitle={t('liveGrid.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('liveGrid.demoSourceNotice')} />}
      />
      <Notice tone="info">{t('liveGrid.readOnly')}</Notice>
      <div className="mt-3">
        <LiveGridConsole initial={initial} />
      </div>
    </>
  )
}
