import { notFound } from 'next/navigation'
import { DevTaskBoard } from '@/components/app/dev-task-board'
import { groupByStatus, positionForUrgency, sortColumn, type BoardRole, type DevTask, type DevTaskEvent } from '@/lib/domain/dev-tasks'

/** Design preview of the developer task board with sample tasks. Development only; nothing is saved. */
const h = (hoursAgo: number) => new Date(Date.UTC(2026, 9, 21, 14) - hoursAgo * 3_600_000).toISOString()
let n = 40
const base = (over: Partial<DevTask>): DevTask => ({
  id: `00000000-0000-4000-8000-0000000000${String(++n).padStart(2, '0')}`, task_number: n, project: 'HHA Workspace', title: '', summary: null,
  urgency: 'normal', status: 'pending', position: n * 1024, why: null, steps: [], done_when: null, report_back: null, do_not_touch: null,
  details: null, due_date: null, source: 'HHA Workspace CTO', created_by: 'HHA Workspace CTO', started_at: null, completed_at: null,
  completion_note: null, archived_at: null, created_at: h(30), updated_at: h(2), ...over,
})

const RAW: DevTask[] = [
  base({ title: 'Finish the heavyhaulagent.com switch checklist', urgency: 'urgent', summary: 'The root domain already serves the Workspace. Finish sign-in, email webhook and the heavyhaulgbt.com redirect.', due_date: '2026-10-22',
    why: 'heavyhaulagent.com moved to the Workspace ahead of the agreed order. Until the checklist is finished, Google sign-in and email delivery events may fail on the new address.',
    steps: ['Report who changed the root domain, when, and what was changed (DNS, Cloudflare rules, site config).', 'Set NEXT_PUBLIC_APP_URL=https://heavyhaulagent.com and restart.', 'Add heavyhaulagent.com to Google sign-in origins and redirect URIs, and to reCAPTCHA.', 'Point the ZeptoMail webhooks to heavyhaulagent.com.', 'Enable the heavyhaulgbt.com → heavyhaulagent.com redirect (same path).', 'Run the section C checks in docs/ADDRESS-SWITCH-WORKSPACE.md.'],
    done_when: 'Every item in sections B and C is checked, and sign-in by email code and by Google works on heavyhaulagent.com.', report_back: 'Each checklist item as done / not done, and the time the redirect went live.', do_not_touch: 'Mail records (MX, SPF, DKIM).' }),
  base({ title: 'Workspace staging environment', urgency: 'high', summary: 'Own database and keys, HHA_ENVIRONMENT=staging, Brain calls off until the staging Brain exists.', created_at: h(70),
    why: 'Synchron keeps its order push off until its 16-case contract test passes against Workspace staging.', steps: ['Create the staging site and database.', 'Set HHA_ENVIRONMENT=staging (trip numbers 100000000–100999999).', 'Leave Brain calls off until staging-brain.heavyhaulagent.com is posted.', 'Post the /api/webhooks/synchron URL on this task.'],
    done_when: 'Staging answers 401 to an unsigned POST /api/webhooks/synchron.' }),
  base({ title: 'Dedicated storage key for the engineering machine', urgency: 'high', summary: 'Least-privilege key, verify, then retire the old one.', created_at: h(26) }),
  base({ title: 'Carrier rule: most readings wins below 50%', summary: 'HH-878851361 → VSP Transport; ties stay needs_confirmation.', created_at: h(20), steps: ['Check the purchase lock first.', 'Update carrier-validation.ts with tests.'] }),
  base({ title: 'Remove the old shared demo accounts from staging', urgency: 'low', created_at: h(10) }),
  base({ title: 'Production deploy and cron schedules', urgency: 'urgent', status: 'ongoing', started_at: h(5), summary: 'Deploy main, confirm permit-retry and permit-expiry schedules.', position: 1024,
    steps: ['Deploy main.', 'Confirm both cron schedules (times only).'], report_back: 'Commit hash in production and the deploy time.' }),
  base({ title: 'S8: receive pushed Synchron orders (contract v0.4.1)', project: 'HHA Workspace', status: 'ongoing', started_at: h(28), position: 2048, summary: 'Unknown event types 2xx and ignored, duplicates once, 8-digit references.' }),
  base({ title: 'Merge B15, B8 and C9 on branch nash', project: 'HHA Brain', urgency: 'high', summary: 'Review, merge through a pull request, deploy, record the time.', created_at: h(40) }),
  base({ title: 'R3 — 9-digit trip-to-order tests', status: 'completed', started_at: h(50), completed_at: h(9), completion_note: 'Mapping and binding tests pass on main (tests/trip-numbers.test.ts).' }),
  base({ title: 'Send the two permit files to the Brain developer', status: 'completed', started_at: h(30), completed_at: h(6), completion_note: 'Sent through a one-time secret; links expire after 24 hours.' }),
  base({ title: 'R7 — carrier validation on production trips', status: 'completed', started_at: h(52), completed_at: h(8) }),
]

// Place the sample pending tasks the way the API places new ones: by urgency.
const TASKS: DevTask[] = RAW.reduce<DevTask[]>((placed, t) => {
  if (t.status !== 'pending') return [...placed, t]
  const column = sortColumn(placed.filter((x) => x.status === 'pending'))
  return [...placed, { ...t, position: positionForUrgency(column, t.urgency) }]
}, [])

const EVENTS: Record<string, DevTaskEvent[]> = Object.fromEntries(TASKS.map((t) => [t.id, [
  { id: `${t.id}-c`, task_id: t.id, action: 'created', from_status: null, to_status: 'pending', actor_kind: 'api', actor_label: 'HHA Workspace CTO', detail: {}, created_at: t.created_at },
  ...(t.started_at ? [{ id: `${t.id}-s`, task_id: t.id, action: 'moved' as const, from_status: 'pending', to_status: 'ongoing', actor_kind: 'developer' as const, actor_label: 'HHA Workspace Developer', detail: {}, created_at: t.started_at }] : []),
  ...(t.urgency === 'urgent' && t.status === 'pending' ? [
    { id: `${t.id}-q`, task_id: t.id, action: 'comment' as const, from_status: 'pending', to_status: 'pending', actor_kind: 'developer' as const, actor_label: 'HHA Workspace Developer', detail: { text: 'Should the redirect keep query strings too?' }, created_at: h(3) },
    { id: `${t.id}-a`, task_id: t.id, action: 'comment' as const, from_status: 'pending', to_status: 'pending', actor_kind: 'api' as const, actor_label: 'HHA Workspace CTO', detail: { text: 'Yes, same path and same query string.' }, created_at: h(2) },
  ] : []),
  ...(t.completed_at ? [{ id: `${t.id}-d`, task_id: t.id, action: 'moved' as const, from_status: 'ongoing', to_status: 'completed', actor_kind: 'developer' as const, actor_label: 'HHA Workspace Developer', detail: {}, created_at: t.completed_at }] : []),
]]))

export default async function DevTasksPreview({ searchParams }: { searchParams: Promise<{ role?: string }> }) {
  if (process.env.NODE_ENV !== 'development') notFound()
  const role: BoardRole = (await searchParams).role === 'developer' ? 'developer' : 'manager'
  const counts = Object.fromEntries(TASKS.map((t) => [t.id, EVENTS[t.id].filter((e) => e.action === 'comment').length]))
  return (
    <main className="min-h-screen bg-neutral-50">
      <div className="mx-auto max-w-7xl space-y-6 px-4 py-8">
        <div>
          <h1 className="text-2xl font-bold">Developer task board</h1>
          <p className="mt-1 max-w-2xl text-sm text-neutral-500">Preview with sample tasks ({role}). Nothing here is saved.</p>
        </div>
        <DevTaskBoard initial={groupByStatus(TASKS)} commentCounts={counts} role={role} apiBase={null} sampleEvents={EVENTS} />
      </div>
    </main>
  )
}
