'use client'

import { useState } from 'react'
import Link from 'next/link'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { STATE_NAMES } from '@/lib/domain/states'
import { PILOT_PREVIEW_SIGNUP_KEY, type PilotPreviewSignup } from '@/app/(auth)/signup/pilot/pilot-signup-wizard'

interface Cap { key: string; label: string; group: 'position' | 'certification' }

/**
 * The claim form (§20–§22). Three parts on one page: what we have (all
 * editable), "What describes you?", the capability check (confirm / remove
 * / add more), then the opt-in choice — not pre-checked.
 *
 * After the claim is recorded, onboarding continues. Answer 4: the goal is a
 * real account; the platform's authentication cannot create one yet (logins
 * come from AUTH_USERS), so the person is handed into the existing pilot
 * signup flow with their details prefilled, and real account creation is
 * the next step of that flow.
 */
export function ClaimForm({ token, initial, capabilityTypes, states }: {
  token: string
  initial: { name: string; company_name: string | null; email: string; phone: string | null; states: string[]; capabilities: Cap[] }
  capabilityTypes: Cap[]
  states: string[]
}) {
  const [type, setType] = useState<'pilot_driver' | 'pilot_company' | null>(null)
  const [form, setForm] = useState({ name: initial.name, company_name: initial.company_name ?? '', email: initial.email, phone: initial.phone ?? '' })
  const [stateList, setStateList] = useState<string[]>(initial.states)
  const [addState, setAddState] = useState('')
  const [keep, setKeep] = useState<string[]>(initial.capabilities.map((c) => c.key))
  const [optIn, setOptIn] = useState(false)
  const [busy, setBusy] = useState(false)
  const [done, setDone] = useState<{ account_type: string } | null>(null)

  const imported = initial.capabilities
  const importedKeys = new Set(imported.map((c) => c.key))
  const addable = capabilityTypes.filter((c) => !importedKeys.has(c.key))

  async function submit() {
    if (!type) { toast.error('Tell us what describes you.'); return }
    setBusy(true)
    const res = await fetch('/api/pilot/claim', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ token, account_type: type, name: form.name, company_name: form.company_name || null, email: form.email, phone: form.phone || null, states: stateList, capability_keys: keep, opt_in: optIn }),
    })
    const json = await res.json().catch(() => ({}))
    setBusy(false)
    if (!res.ok) { toast.error(json.error ?? 'Could not claim the profile.'); return }
    try {
      const payload: PilotPreviewSignup = { type, name: form.name, email: form.email, phone: form.phone, company: form.company_name || null }
      sessionStorage.setItem(PILOT_PREVIEW_SIGNUP_KEY, JSON.stringify(payload))
    } catch { /* storage unavailable */ }
    setDone({ account_type: type })
  }

  if (done) {
    return (
      <div className="space-y-4 text-center">
        <p className="rounded-xl border border-green-200 bg-green-50 p-4 text-sm text-green-800">✓ Your pilot profile is claimed{optIn ? ' and you are opted in to future pilot car requests' : ''}.</p>
        <p className="text-sm text-neutral-600">Next, create your HeavyHaul Agent account so you can sign in, confirm your service states, capabilities and vehicle, and manage your alerts.</p>
        <Link href="/signup/pilot" className="block w-full rounded-lg bg-[#0f1b2d] py-2.5 text-sm font-bold text-white">Create my account →</Link>
        <p className="text-xs text-neutral-500">Your details are carried over so you do not type them twice.</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* What we have (§20) — everything editable */}
      <section className="space-y-3">
        <p className="text-[10px] font-bold uppercase tracking-[0.14em] text-neutral-500">What we have — correct anything that is wrong</p>
        <div className="grid gap-3 sm:grid-cols-2">
          <Field label="Name" value={form.name} onChange={(v) => setForm({ ...form, name: v })} required />
          <Field label="Company (leave blank if none)" value={form.company_name} onChange={(v) => setForm({ ...form, company_name: v })} />
          <Field label="Email" type="email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} required />
          <Field label="Phone" type="tel" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} />
        </div>
        <div>
          <Label className="text-xs">States you serve</Label>
          <div className="mt-1 flex flex-wrap items-center gap-1.5">
            {stateList.map((s) => (
              <span key={s} className="inline-flex items-center gap-1 rounded-full bg-neutral-100 px-2.5 py-1 text-xs font-semibold">
                {s} — {STATE_NAMES[s] ?? s}
                <button type="button" aria-label={`Remove ${s}`} onClick={() => setStateList(stateList.filter((x) => x !== s))} className="text-neutral-500 hover:text-red-700">×</button>
              </span>
            ))}
            <select value={addState} onChange={(e) => { const v = e.target.value; if (v && !stateList.includes(v)) setStateList([...stateList, v]); setAddState('') }} className="h-8 rounded-md border bg-white px-2 text-xs">
              <option value="">+ Add a state</option>
              {states.filter((s) => !stateList.includes(s)).map((s) => <option key={s} value={s}>{s} — {STATE_NAMES[s]}</option>)}
            </select>
          </div>
        </div>
      </section>

      {/* What describes you (§20) */}
      <section className="space-y-2">
        <Label>What describes you?</Label>
        <div className="grid gap-2">
          {([
            ['pilot_driver', 'Pilot Driver', 'I physically perform pilot / escort work'],
            ['pilot_company', 'Pilot Company / Pilot Dispatch', 'I dispatch or manage pilot cars and pilot drivers'],
          ] as const).map(([value, label, desc]) => (
            <button key={value} type="button" onClick={() => setType(value)} className={`rounded-xl border p-3 text-left transition ${type === value ? 'border-[#0f1b2d] bg-[#0f1b2d] text-white' : 'hover:border-neutral-400'}`}>
              <p className="text-sm font-bold">{label}</p>
              <p className={`text-xs ${type === value ? 'text-neutral-300' : 'text-neutral-500'}`}>{desc}</p>
            </button>
          ))}
        </div>
      </section>

      {/* Capabilities (§21–§22) */}
      <section className="space-y-2">
        <p className="text-sm font-semibold">We currently have the following capabilities associated with your profile.</p>
        <p className="text-xs text-neutral-500">These came from a directory listing — they are not verified by HeavyHaul Agent. Confirm the ones that are right, remove the ones that are not, and add anything missing.</p>
        {imported.length === 0 && <p className="text-xs text-neutral-500">No capabilities on file yet — add yours below.</p>}
        <div className="flex flex-wrap gap-1.5">
          {imported.map((c) => {
            const on = keep.includes(c.key)
            return (
              <button key={c.key} type="button" onClick={() => setKeep(on ? keep.filter((k) => k !== c.key) : [...keep, c.key])} className={`rounded-full px-3 py-1.5 text-xs font-semibold ring-1 ring-inset ${on ? 'bg-green-50 text-green-900 ring-green-300' : 'bg-white text-neutral-400 line-through ring-neutral-200'}`} title={on ? 'Confirmed — click to remove' : 'Removed — click to keep'}>
                {on ? '✓ ' : ''}{c.label}<span className="ml-1 font-normal text-neutral-400 no-underline">· imported</span>
              </button>
            )
          })}
        </div>
        {/* Escort positions only — certifications (WITPAC, CEVO, CSE, Passport,
            NY Certified) are activated on the pilot's profile later (Nash, 2026-09-14). */}
        <details className="rounded-xl border bg-neutral-50 p-3">
          <summary className="cursor-pointer text-xs font-semibold">Add more</summary>
          <div className="mt-2">
            <p className="text-[10px] font-bold uppercase tracking-wide text-neutral-500">Escort positions</p>
            <div className="mt-1 flex flex-wrap gap-1.5">
              {addable.filter((c) => c.group === 'position').map((c) => {
                const on = keep.includes(c.key)
                return <button key={c.key} type="button" onClick={() => setKeep(on ? keep.filter((k) => k !== c.key) : [...keep, c.key])} className={`rounded-full px-3 py-1.5 text-xs font-semibold ring-1 ring-inset ${on ? 'bg-[#0f1b2d] text-white ring-[#0f1b2d]' : 'bg-white ring-neutral-200'}`}>{c.label}</button>
              })}
            </div>
          </div>
        </details>
      </section>

      {/* Opt-in — not pre-checked */}
      <label className="flex cursor-pointer items-start gap-2 rounded-xl border p-3 text-sm">
        <input type="checkbox" checked={optIn} onChange={(e) => setOptIn(e.target.checked)} className="mt-0.5 h-4 w-4 accent-[#0f1b2d]" />
        <span>Yes — send me future pilot car requests for the states above. <span className="block text-xs text-neutral-500">You can change this any time. Without it we will not send you pilot job alerts.</span></span>
      </label>

      <Button type="button" className="w-full" disabled={busy || !form.name.trim() || !form.email.trim() || stateList.length === 0} onClick={submit}>
        {busy ? 'Saving…' : 'Claim My Pilot Profile'}
      </Button>
    </div>
  )
}

function Field({ label, value, onChange, type = 'text', required }: { label: string; value: string; onChange: (v: string) => void; type?: string; required?: boolean }) {
  const id = `claim-${label.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`
  return (
    <div className="space-y-1.5">
      <Label htmlFor={id}>{label}{required && <span className="ml-1 text-red-600">*</span>}</Label>
      <Input id={id} type={type} value={value} onChange={(e) => onChange(e.target.value)} required={required} />
    </div>
  )
}
