'use client'

import { AppLayout } from '@/components/layout'
import { IwoooSReadOnlyBridge } from '@/components/security/iwooos-read-only-bridge'
import {
  Activity,
  ArrowRight,
  Bot,
  CheckCircle2,
  ClipboardList,
  Code2,
  ExternalLink,
  FileCheck2,
  GitBranch,
  Gauge,
  ListChecks,
  LockKeyhole,
  SearchCheck,
  ShieldCheck,
  Workflow,
} from 'lucide-react'
import { useTranslations } from 'next-intl'

const agents = [
  { name: 'Hermes', roleKey: 'hermes', state: 'wired' },
  { name: 'OpenClaw', roleKey: 'openclaw', state: 'wired' },
  { name: 'Elephant Alpha', roleKey: 'elephantAlpha', state: 'wired' },
  { name: 'NemoTron', roleKey: 'nemotron', state: 'standby' },
]

const stages = [
  { key: 'push' },
  { key: 'start' },
  { key: 'scan' },
  { key: 'classify' },
  { key: 'report' },
]

const handoffFlags = [
  'codex_handoff_mode=read_only_candidate',
  'codex_auto_coding_enabled=false',
  'runtime_execution_authorized=false',
  'production_deploy_authorized=false',
]

const codexHandoffLanes = [
  {
    key: 'draftable',
    icon: Code2,
    className: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-100',
    iconClassName: 'text-emerald-300',
  },
  {
    key: 'approvalRequired',
    icon: FileCheck2,
    className: 'border-amber-500/30 bg-amber-500/10 text-amber-100',
    iconClassName: 'text-amber-300',
  },
  {
    key: 'blocked',
    icon: LockKeyhole,
    className: 'border-rose-500/30 bg-rose-500/10 text-rose-100',
    iconClassName: 'text-rose-300',
  },
]

const codexCandidateWork = [
  { id: 'CR-CX-01', key: 'frontendExperience', state: 'candidate' },
  { id: 'CR-CX-02', key: 'testCoverage', state: 'candidate' },
  { id: 'CR-CX-03', key: 'documentationSync', state: 'candidate' },
  { id: 'CR-CX-04', key: 'lowRiskRefactor', state: 'candidate' },
  { id: 'CR-BLOCK-01', key: 'runtimeBlocked', state: 'blocked' },
]

const approvalFlowSteps = [
  'candidate',
  'manualApproval',
  'codexTask',
  'patch',
  'guards',
  'deploy',
]

const summaryCards = [
  { key: 'source', icon: GitBranch, iconClassName: 'text-emerald-300' },
  { key: 'trigger', icon: Activity, iconClassName: 'text-sky-300' },
  { key: 'gate', icon: ShieldCheck, iconClassName: 'text-amber-300' },
  { key: 'report', icon: Gauge, iconClassName: 'text-lime-300' },
]

export default function CodeReviewPage({ params }: { params: { locale: string } }) {
  const t = useTranslations('codeReview')
  const evidenceHref = `/${params.locale}/awooop/runs`

  return (
    <AppLayout locale={params.locale}>
      <main className="min-h-screen bg-[#0f1115] text-gray-100">
        <div className="mx-auto flex max-w-7xl flex-col gap-6 px-4 py-6 sm:px-6 lg:px-8">
          <header className="flex flex-col gap-4 border-b border-gray-800 pb-5 md:flex-row md:items-end md:justify-between">
            <div>
              <div className="flex items-center gap-2 text-xs font-mono uppercase text-emerald-300">
                <SearchCheck className="h-4 w-4" />
                {t('header.eyebrow')}
              </div>
              <h1 className="mt-2 text-2xl font-semibold text-white">{t('header.title')}</h1>
              <p className="mt-1 text-sm text-gray-400">{t('header.subtitle')}</p>
            </div>
            <a
              href={evidenceHref}
              className="inline-flex min-h-10 items-center justify-center gap-2 rounded border border-emerald-500/40 px-3 py-2 text-sm font-medium text-emerald-200 transition-colors hover:border-emerald-300 hover:bg-emerald-500/10"
            >
              <ExternalLink className="h-4 w-4" />
              {t('header.evidenceLink')}
            </a>
          </header>

          <IwoooSReadOnlyBridge variant="dark" />

          <section
            id="code-review-codex-handoff-board"
            data-testid="code-review-codex-handoff-board"
            className="grid min-w-0 gap-4 rounded border border-gray-800 bg-gray-950 p-4 lg:grid-cols-[minmax(0,0.92fr)_minmax(0,1.08fr)]"
          >
            <div className="flex min-w-0 flex-col justify-between gap-5">
              <div className="min-w-0">
                <div className="flex items-center gap-2 text-xs font-mono uppercase text-sky-300">
                  <ClipboardList className="h-4 w-4" />
                  {t('handoff.eyebrow')}
                </div>
                <h2 className="mt-2 text-xl font-semibold text-white">{t('handoff.title')}</h2>
                <p className="mt-2 max-w-xl text-sm leading-6 text-gray-400">{t('handoff.subtitle')}</p>
              </div>
              <div className="grid gap-2 text-xs font-mono text-gray-400 sm:grid-cols-2">
                {handoffFlags.map((flag) => (
                  <div key={flag} className="min-w-0 break-all rounded border border-gray-800 bg-black/25 px-3 py-2">
                    {flag}
                  </div>
                ))}
              </div>
            </div>

            <div className="grid min-w-0 gap-3 md:grid-cols-3">
              {codexHandoffLanes.map((lane, index) => {
                const Icon = lane.icon
                return (
                  <div
                    key={lane.key}
                    className={`flex min-h-[12rem] min-w-0 flex-col rounded border p-3 ${lane.className}`}
                  >
                    <div className="flex items-center justify-between gap-3">
                      <Icon className={`h-5 w-5 ${lane.iconClassName}`} />
                      <span className="font-mono text-xl font-semibold">{t(`handoff.lanes.${lane.key}.metric` as never)}</span>
                    </div>
                    <div className="mt-4 text-sm font-semibold text-white">{t(`handoff.lanes.${lane.key}.title` as never)}</div>
                    <p className="mt-2 text-sm leading-5 text-gray-300">{t(`handoff.lanes.${lane.key}.detail` as never)}</p>
                    <div className="mt-auto pt-4 text-xs leading-5 text-gray-400">{t(`handoff.lanes.${lane.key}.guard` as never)}</div>
                    {index < codexHandoffLanes.length - 1 ? (
                      <ArrowRight className="mt-3 hidden h-4 w-4 self-end text-gray-600 md:block" />
                    ) : null}
                  </div>
                )
              })}
            </div>
          </section>

          <section
            data-testid="code-review-codex-candidate-work"
            className="min-w-0 rounded border border-gray-800 bg-gray-950"
          >
            <div className="grid min-w-0 gap-2 border-b border-gray-800 px-4 py-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-center">
              <div className="min-w-0">
                <div className="flex items-center gap-2 break-words text-sm font-semibold text-white">
                  <ListChecks className="h-4 w-4 text-emerald-300" />
                  {t('candidateQueue.title')}
                </div>
                <div className="mt-1 break-words text-xs text-gray-500">{t('candidateQueue.subtitle')}</div>
              </div>
              <div className="min-w-0 max-w-full break-all rounded border border-emerald-500/30 px-3 py-1 text-xs font-mono text-emerald-200 md:justify-self-end">
                action_buttons_allowed=false
              </div>
            </div>
            <div className="hidden grid-cols-[7rem_8rem_1.1fr_1.15fr_8rem_6rem] gap-3 border-b border-gray-800 px-4 py-2 text-xs font-mono uppercase text-gray-500 md:grid">
              <span>{t('candidateQueue.columns.id')}</span>
              <span>{t('candidateQueue.columns.track')}</span>
              <span>{t('candidateQueue.columns.finding')}</span>
              <span>{t('candidateQueue.columns.handoff')}</span>
              <span>{t('candidateQueue.columns.gate')}</span>
              <span>{t('candidateQueue.columns.state')}</span>
            </div>
            <div className="divide-y divide-gray-800">
              {codexCandidateWork.map((item) => (
                <div
                  key={item.id}
                  className="grid gap-3 px-4 py-3 text-sm md:grid-cols-[7rem_8rem_1.1fr_1.15fr_8rem_6rem] md:items-center"
                >
                  <span className="min-w-0 break-words font-mono text-gray-500">{item.id}</span>
                  <span className="min-w-0 break-words font-semibold text-white">
                    {t(`candidateQueue.items.${item.key}.track` as never)}
                  </span>
                  <span className="min-w-0 break-words text-gray-400">
                    {t(`candidateQueue.items.${item.key}.finding` as never)}
                  </span>
                  <span className="min-w-0 break-words text-gray-300">
                    {t(`candidateQueue.items.${item.key}.handoff` as never)}
                  </span>
                  <span className="min-w-0 break-words text-gray-500">
                    {t(`candidateQueue.items.${item.key}.gate` as never)}
                  </span>
                  <span
                    className={
                      item.state === 'blocked'
                        ? 'justify-self-start rounded bg-rose-500/10 px-2 py-1 text-xs font-mono text-rose-200'
                        : 'justify-self-start rounded bg-emerald-500/10 px-2 py-1 text-xs font-mono text-emerald-200'
                    }
                  >
                    {t(`states.${item.state}` as never)}
                  </span>
                </div>
              ))}
            </div>
          </section>

          <section className="grid gap-3 md:grid-cols-4">
            {summaryCards.map((card) => {
              const Icon = card.icon
              return (
                <div key={card.key} className="rounded border border-gray-800 bg-gray-950 p-4">
                  <div className="flex items-center gap-2 text-xs text-gray-400">
                    <Icon className={`h-4 w-4 ${card.iconClassName}`} />
                    {t(`summaryCards.${card.key}.label` as never)}
                  </div>
                  <div className="mt-3 text-lg font-semibold text-white">{t(`summaryCards.${card.key}.value` as never)}</div>
                  <div className="mt-1 text-xs text-gray-500">{t(`summaryCards.${card.key}.detail` as never)}</div>
                </div>
              )
            })}
          </section>

          <section className="rounded border border-gray-800 bg-gray-950 p-4">
            <div className="flex items-center gap-2 text-sm font-semibold text-white">
              <Workflow className="h-4 w-4 text-sky-300" />
              {t('approvalFlow.title')}
            </div>
            <div className="mt-3 grid gap-2 md:grid-cols-6">
              {approvalFlowSteps.map((step, index) => (
                <div key={step} className="min-w-0 rounded border border-gray-800 bg-black/20 px-3 py-3">
                  <div className="font-mono text-xs text-gray-500">{String(index + 1).padStart(2, '0')}</div>
                  <div className="mt-2 text-sm font-semibold text-white">{t(`approvalFlow.steps.${step}.title` as never)}</div>
                  <div className="mt-1 text-xs leading-5 text-gray-400">{t(`approvalFlow.steps.${step}.detail` as never)}</div>
                </div>
              ))}
            </div>
          </section>

          <section className="grid gap-6 lg:grid-cols-[1.1fr_0.9fr]">
            <div className="space-y-3">
              <div className="flex items-center gap-2 text-sm font-semibold text-white">
                <CheckCircle2 className="h-4 w-4 text-emerald-300" />
                {t('reviewFlow.title')}
              </div>
              <div className="grid gap-2">
                {stages.map((stage, index) => (
                  <div
                    key={stage.key}
                    className="grid grid-cols-[2rem_8rem_1fr] items-center rounded border border-gray-800 bg-gray-950 px-3 py-2 text-sm"
                  >
                    <span className="font-mono text-gray-500">{String(index + 1).padStart(2, '0')}</span>
                    <span className="font-mono text-emerald-200">{t(`reviewFlow.stages.${stage.key}.label` as never)}</span>
                    <span className="truncate text-gray-300">{t(`reviewFlow.stages.${stage.key}.state` as never)}</span>
                  </div>
                ))}
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex items-center gap-2 text-sm font-semibold text-white">
                <Bot className="h-4 w-4 text-sky-300" />
                {t('agents.title')}
              </div>
              <div className="grid gap-2">
                {agents.map((agent) => (
                  <div
                    key={agent.name}
                    className="grid grid-cols-[8rem_1fr_4.5rem] items-center rounded border border-gray-800 bg-gray-950 px-3 py-2 text-sm"
                  >
                    <span className="font-semibold text-white">{agent.name}</span>
                    <span className="truncate text-gray-400">{t(`agents.roles.${agent.roleKey}` as never)}</span>
                    <span className="justify-self-end rounded bg-emerald-500/10 px-2 py-1 text-xs font-mono text-emerald-200">
                      {t(`agentStates.${agent.state}` as never)}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </section>
        </div>
      </main>
    </AppLayout>
  )
}
