'use client'

import { useState } from 'react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import type { PilotAccountType } from '@/lib/domain/pilot'

/**
 * Pilot signup — Phase 1 replica (article §6–§9), trimmed to three steps.
 *
 * Nash, 2026-09-12: "you should ask to validate my email. And once I validate
 * my email, it should let me go directly into the pilot dashboard. Now step
 * four, five, six, and seven it's something that I should be able to do it
 * after I logged in… I would like to have these three steps to let him in to
 * join. And then the other steps are done on the page itself, on the my
 * assignments page." Documents, vehicle and capabilities therefore live in
 * the dashboards as unfinished tasks (see pilot-driver-view.tsx).
 *
 * No account is created, no email is sent, nothing is stored server-side.
 * The typed details are handed to the dashboard preview through
 * sessionStorage so the "fresh account" state shows the right name and
 * company; no password field because credentials are a later phase.
 */

const STEPS = ['Account type', 'Details', 'Validate email'] as const

/** sessionStorage key read by the dashboard previews. */
export const PILOT_PREVIEW_SIGNUP_KEY = 'hha-pilot-preview-signup'

export interface PilotPreviewSignup {
  type: PilotAccountType
  name: string
  email: string
  phone: string
  /** Pilot driver only: the company they said they work with (pending request). */
  company: string | null
}

export function PilotSignupWizard() {
  const [step, setStep] = useState(0)
  const [type, setType] = useState<PilotAccountType | null>(null)
  const [worksWithCompany, setWorksWithCompany] = useState<boolean | null>(null)
  const [person, setPerson] = useState({ name: '', email: '', phone: '' })
  const [driverCompany, setDriverCompany] = useState({ name: '', phone: '', email: '', dispatcher: '' })
  const [company, setCompany] = useState({ name: '', address: '', phone: '', email: '', contact: '' })
  const [emailSent, setEmailSent] = useState(false)
  const [emailVerified, setEmailVerified] = useState(false)

  const contactEmail = type === 'pilot_company' ? company.email : person.email

  const detailsOk =
    type === 'pilot_driver'
      ? person.name && person.email && person.phone && worksWithCompany !== null && (!worksWithCompany || driverCompany.name)
      : company.name && company.address && company.phone && company.email && company.contact

  const canNext = [type !== null, Boolean(detailsOk)][step]

  const dashboardHref = `/${type === 'pilot_company' ? 'pd' : 'pc'}-dashboard?onboarding=new`

  function rememberForPreview() {
    if (!type) return
    const payload: PilotPreviewSignup = {
      type,
      name: type === 'pilot_company' ? company.contact : person.name,
      email: contactEmail,
      phone: type === 'pilot_company' ? company.phone : person.phone,
      company: type === 'pilot_company' ? company.name : worksWithCompany ? driverCompany.name : null,
    }
    try {
      sessionStorage.setItem(PILOT_PREVIEW_SIGNUP_KEY, JSON.stringify(payload))
    } catch {
      // storage unavailable — the dashboard falls back to its generic new-account persona
    }
  }

  return (
    <main className="min-h-screen bg-neutral-50 p-4">
      <div className="mx-auto max-w-2xl">
        <div className="mb-4 rounded-xl border border-amber-300 bg-amber-50 px-4 py-2.5 text-xs text-amber-900">
          <span className="font-semibold">Design preview — pilot signup.</span> Nothing is saved, no email is sent, no account or credentials are created. Admin only.
          <Link href="/pd-dashboard" className="ml-2 rounded-full bg-white/70 px-2.5 py-0.5 font-semibold hover:bg-white">Pilot Dispatch</Link>
          <Link href="/pc-dashboard" className="ml-1.5 rounded-full bg-white/70 px-2.5 py-0.5 font-semibold hover:bg-white">Pilot Driver</Link>
        </div>

        <ol className="mb-4 flex flex-wrap gap-1.5 text-[11px] font-semibold">
          {STEPS.map((s, i) => (
            <li key={s} className={`rounded-full px-2.5 py-1 ring-1 ring-inset ${i === step ? 'bg-[#0f1b2d] text-white ring-[#0f1b2d]' : i < step ? 'bg-green-50 text-green-800 ring-green-200' : 'bg-white text-neutral-500 ring-neutral-200'}`}>
              {i + 1}. {s}
            </li>
          ))}
          <li className="rounded-full bg-white px-2.5 py-1 text-neutral-400 ring-1 ring-inset ring-neutral-200">Then: documents, vehicle, capabilities — inside your dashboard</li>
        </ol>

        <Card>
          <CardHeader className="text-center">
            <div className="mx-auto mb-2 grid h-11 w-11 place-items-center rounded-xl bg-[#0f1b2d] text-lg font-extrabold text-[#f5a623]">H</div>
            <CardTitle className="text-xl">
              {step === 0 && 'Create your pilot car account'}
              {step === 1 && (type === 'pilot_company' ? 'Your pilot company' : 'About you')}
              {step === 2 && 'Validate your email'}
            </CardTitle>
            <CardDescription>
              {step === 0 && 'Pilot cars have their own account types. This choice controls the rest of onboarding.'}
              {step === 1 && (type === 'pilot_company' ? 'A pilot company gets a company profile that manages drivers, vehicles, assignments and documents.' : 'Your contact details, and whether you work under a pilot company.')}
              {step === 2 && 'HeavyHaul Agent sends trip assignments, permit access, route access and document requests by email. Once validated you go straight to your dashboard.'}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {step === 0 && (
              <div className="space-y-2">
                <Label>Are you signing up as a Pilot Driver or a Pilot Company?</Label>
                <div className="grid gap-2">
                  {([
                    ['pilot_driver', 'Pilot Driver', 'I physically perform pilot / escort work'],
                    ['pilot_company', 'Pilot Company', '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>
              </div>
            )}

            {step === 1 && type === 'pilot_driver' && (
              <>
                <Field label="Full name" value={person.name} onChange={(v) => setPerson({ ...person, name: v })} required />
                <Field label="Email" type="email" value={person.email} onChange={(v) => setPerson({ ...person, email: v })} required />
                <Field label="Phone number" type="tel" value={person.phone} onChange={(v) => setPerson({ ...person, phone: v })} required />
                <div className="space-y-2 pt-2">
                  <Label>Do you work under a pilot company?</Label>
                  <div className="grid gap-2">
                    {([
                      [false, 'I am independent / self-employed'],
                      [true, 'I work with a pilot company'],
                    ] as const).map(([value, label]) => (
                      <button key={String(value)} type="button" onClick={() => setWorksWithCompany(value)} className={`rounded-xl border p-3 text-left text-sm font-semibold transition ${worksWithCompany === value ? 'border-[#0f1b2d] bg-[#0f1b2d] text-white' : 'hover:border-neutral-400'}`}>
                        {label}
                      </button>
                    ))}
                  </div>
                </div>
                {worksWithCompany && (
                  <div className="space-y-3 rounded-xl border border-neutral-200 bg-neutral-50 p-3">
                    <Field label="Pilot company name" value={driverCompany.name} onChange={(v) => setDriverCompany({ ...driverCompany, name: v })} required />
                    <Field label="Company phone, if known" value={driverCompany.phone} onChange={(v) => setDriverCompany({ ...driverCompany, phone: v })} />
                    <Field label="Company email, if known" value={driverCompany.email} onChange={(v) => setDriverCompany({ ...driverCompany, email: v })} />
                    <Field label="Dispatcher name, if known" value={driverCompany.dispatcher} onChange={(v) => setDriverCompany({ ...driverCompany, dispatcher: v })} />
                    <p className="text-xs text-neutral-500">
                      This does not verify the relationship. It creates a <span className="font-semibold">pending relationship request</span> the company must approve. Once approved, the company can upload your required documents for you — you can also upload them yourself.
                    </p>
                  </div>
                )}
                {worksWithCompany === false && (
                  <p className="text-xs text-neutral-500">As an independent pilot driver, only you can upload your documents. You will do that from your dashboard.</p>
                )}
              </>
            )}
            {step === 1 && type === 'pilot_company' && (
              <>
                <Field label="Company name" value={company.name} onChange={(v) => setCompany({ ...company, name: v })} required />
                <Field label="Company address" value={company.address} onChange={(v) => setCompany({ ...company, address: v })} required />
                <Field label="Company phone number" type="tel" value={company.phone} onChange={(v) => setCompany({ ...company, phone: v })} required />
                <Field label="Company email" type="email" value={company.email} onChange={(v) => setCompany({ ...company, email: v })} required />
                <Field label="Main contact / dispatcher name" value={company.contact} onChange={(v) => setCompany({ ...company, contact: v })} required />
              </>
            )}

            {step === 2 && (
              <div className="space-y-3 text-center">
                <p className="text-sm">
                  We will send a validation link to <span className="font-semibold">{contactEmail || 'your email'}</span>.
                </p>
                {!emailSent ? (
                  <Button type="button" className="w-full" onClick={() => setEmailSent(true)}>Send validation email</Button>
                ) : !emailVerified ? (
                  <div className="space-y-3">
                    <p className="rounded-xl border border-blue-200 bg-blue-50 p-4 text-sm text-blue-900">
                      Check your inbox and open the link. <span className="block text-xs text-blue-800/80">Preview: no email is sent in this phase — use the button below to simulate the click.</span>
                    </p>
                    <Button type="button" variant="outline" className="w-full" onClick={() => setEmailVerified(true)}>I clicked the link (simulate)</Button>
                    <button type="button" className="text-xs text-neutral-500 underline">Resend</button>
                  </div>
                ) : (
                  <div className="space-y-3">
                    <p className="rounded-xl border border-green-200 bg-green-50 p-4 text-sm text-green-800">✓ Email validated. You&apos;re in.</p>
                    <Link href={dashboardHref} onClick={rememberForPreview} className="block w-full rounded-lg bg-[#0f1b2d] py-2.5 text-sm font-bold text-white">
                      Go to my {type === 'pilot_company' ? 'pilot dispatch dashboard' : 'pilot dashboard'} →
                    </Link>
                    <p className="text-xs text-neutral-500">
                      Documents, {type === 'pilot_company' ? 'units' : 'your vehicle'} and capabilities are waiting for you there as unfinished tasks.
                    </p>
                  </div>
                )}
              </div>
            )}

            <div className="flex items-center justify-between pt-2">
              <Button type="button" variant="ghost" disabled={step === 0} onClick={() => setStep(step - 1)}>Back</Button>
              {step < STEPS.length - 1 && (
                <Button type="button" disabled={!canNext} onClick={() => setStep(step + 1)}>Continue</Button>
              )}
            </div>
            <p className="text-center text-xs text-neutral-500">
              Already have an account? <Link href="/login" className="font-medium text-neutral-900 underline">Sign in</Link>
            </p>
          </CardContent>
        </Card>
      </div>
    </main>
  )
}

function Field({ label, value, onChange, type = 'text', required }: { label: string; value: string; onChange: (v: string) => void; type?: string; required?: boolean }) {
  const id = `pilot-${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>
  )
}
