import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { DecisionBoard, type DecisionView } from '@/components/intelligence/decision-board'
import { DemoDataBadge, PageHeader, Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { listDecisions, storedConfidence } from '@/lib/services/decision-service'

export const metadata: Metadata = { title: 'Decision Records' }
export const dynamic = 'force-dynamic'

/** Decision records and the approval workflow (§13, §41). */
export default async function DecisionsPage() {
  const user = await getCurrentUser()
  const { t } = await getI18n()
  if (!user?.permissions.has('decisions.read')) return <PermissionGate />

  const records = await listDecisions({ limit: 25 })
  const decisions: DecisionView[] = records.map((record) => ({
    code: record.code,
    assetCode: record.assetCode,
    title: record.title,
    titleAr: record.titleAr,
    rationale: record.rationale,
    rationaleAr: record.rationaleAr,
    status: record.status,
    riskBefore: record.riskBefore,
    riskAfter: record.riskAfter,
    createdAt: record.createdAt.getTime(),
    outcome: record.outcome,
    outcomeAr: record.outcomeAr,
    confidence: {
      overall: storedConfidence(record).overall,
      band: storedConfidence(record).band,
      isLowData: storedConfidence(record).isLowData,
    },
    approvals: record.approvals.map((approval) => ({
      step: approval.step,
      decision: approval.decision,
      userName: approval.userName,
      userNameAr: approval.userNameAr,
      comment: approval.comment,
      commentAr: approval.commentAr,
      decidedAt: approval.decidedAt?.getTime() ?? null,
    })),
  }))

  return (
    <>
      <PageHeader
        title={t('decisions.title')}
        subtitle={t('decisions.subtitle')}
        badge={<DemoDataBadge label={t('common.simulationOnly')} title={t('selfHealing.simulationOnly')} />}
      />

      <Panel className="mb-4">
        <PanelHeader title={t('decisions.workflow')} />
        <PanelBody className="pt-0">
          <p className="text-xs leading-relaxed text-text-muted">{t('selfHealing.simulationOnly')}</p>
        </PanelBody>
      </Panel>

      <DecisionBoard
        decisions={decisions}
        canApprove={user.permissions.has('decisions.approve')}
        canSupervise={user.permissions.has('decisions.supervise')}
      />
    </>
  )
}
