'use client'

import { useRef, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Alert, AlertDescription } from '@/components/ui/alert'

type PermitPath = 'upload' | 'synchron'

export function IntakeForm({
  slug,
  brokerName,
  forcedPath = null,
  paymentDefault = null,
}: {
  slug: string
  brokerName: string
  /** Broker defaults (§23): a hard default hides the other path entirely. */
  forcedPath?: PermitPath | null
  /** Broker's default payment party — explained clearly on the Synchron path.
      When the broker's default is 'ask', payment responsibility stays UNSET
      here (open question for Nash: who sets it for intake-created Synchron
      trips — the broker chooses per the workflow doc, so we never guess). */
  paymentDefault?: 'broker' | 'carrier' | null
}) {
  const formRef = useRef<HTMLFormElement>(null)
  const [path, setPath] = useState<PermitPath>(forcedPath ?? 'upload')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [result, setResult] = useState<{ trip_ref: string; invite_url: string | null } | null>(null)
  const [rateConName, setRateConName] = useState<string | null>(null)
  const [permitNames, setPermitNames] = useState<string[]>([])

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setError(null)
    setSubmitting(true)
    try {
      const fd = new FormData(e.currentTarget)
      fd.set('slug', slug)
      fd.set('permit_source', path)
      const res = await fetch('/api/intake', { method: 'POST', body: fd })
      const json = await res.json()
      if (!res.ok) {
        setError(json.error ?? 'Submission failed. Please try again.')
        return
      }
      setResult({ trip_ref: json.trip_ref, invite_url: json.invite_url })
    } catch {
      setError('Network error. Please try again.')
    } finally {
      setSubmitting(false)
    }
  }

  if (result) {
    return (
      <Card className="mt-6 border-green-200 bg-green-50">
        <CardContent className="py-8 text-center">
          <p className="text-3xl">✅</p>
          <h2 className="mt-3 text-lg font-bold text-green-800">Request received</h2>
          <p className="mx-auto mt-2 max-w-md text-sm leading-relaxed text-neutral-600">
            Trip <span className="font-mono font-semibold">{result.trip_ref}</span> was created and{' '}
            {brokerName} has been notified. Use your secure link to open the trip workspace,
            track status, and add anything that&apos;s missing:
          </p>
          {result.invite_url && (
            <a
              href={result.invite_url}
              className="mt-4 inline-block break-all rounded-lg bg-neutral-900 px-4 py-2.5 text-sm font-semibold text-white"
            >
              Open my trip workspace →
            </a>
          )}
          <p className="mt-3 text-xs text-neutral-500">
            This link was also recorded for {`the dispatcher email you provided`}.
          </p>
        </CardContent>
      </Card>
    )
  }

  return (
    <form ref={formRef} onSubmit={onSubmit} className="mt-6 space-y-5">
      {error && (
        <Alert variant="destructive">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {/* honeypot */}
      <input type="text" name="website" tabIndex={-1} autoComplete="off" className="hidden" aria-hidden />

      <Card>
        <CardContent className="space-y-4 pt-6">
          <div className="space-y-2">
            <Label>
              Rate confirmation <span className="text-red-600">*</span>
            </Label>
            <label className="flex cursor-pointer flex-col items-center gap-1.5 rounded-xl border-2 border-dashed border-neutral-300 bg-neutral-50 px-4 py-8 text-center transition hover:border-neutral-500">
              <span className="text-2xl">📄</span>
              <span className="text-sm font-medium">
                {rateConName ?? 'Drag & drop or tap to choose the rate confirmation'}
              </span>
              <span className="text-xs text-neutral-500">PDF, JPG, PNG, or DOCX · max 25MB</span>
              <input
                type="file"
                name="rate_confirmation"
                required
                accept=".pdf,.jpg,.jpeg,.png,.docx"
                className="hidden"
                onChange={(e) => setRateConName(e.target.files?.[0]?.name ?? null)}
              />
            </label>
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="carrier_company">
                Carrier company <span className="text-red-600">*</span>
              </Label>
              <Input id="carrier_company" name="carrier_company" required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="contact_name">
                Dispatcher name <span className="text-red-600">*</span>
              </Label>
              <Input id="contact_name" name="contact_name" required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="contact_email">
                Dispatcher email <span className="text-red-600">*</span>
              </Label>
              <Input id="contact_email" name="contact_email" type="email" required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="contact_phone">
                Dispatcher phone <span className="text-red-600">*</span>
              </Label>
              <Input id="contact_phone" name="contact_phone" type="tel" required />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="notes">Notes or comments</Label>
            <Textarea id="notes" name="notes" rows={3} placeholder="Anything the team should know…" />
          </div>
        </CardContent>
      </Card>

      {/* The mandatory two-path choice from the meeting */}
      <Card>
        <CardContent className="pt-6">
          <Label className="mb-3 block">
            Permits for this load <span className="text-red-600">*</span>
          </Label>
          <div className="grid gap-3 sm:grid-cols-2" role="radiogroup">
            {(forcedPath === null || forcedPath === 'upload') && (
              <button
                type="button"
                role="radio"
                aria-checked={path === 'upload'}
                onClick={() => setPath('upload')}
                className={`rounded-xl border p-4 text-left transition ${
                  path === 'upload'
                    ? 'border-neutral-900 bg-neutral-900 text-white'
                    : 'border-neutral-200 bg-white hover:border-neutral-400'
                }`}
              >
                <p className="font-semibold">I have my own permits</p>
                <p className={`mt-1 text-xs ${path === 'upload' ? 'text-neutral-300' : 'text-neutral-500'}`}>
                  Upload existing permits from any provider
                </p>
              </button>
            )}
            {(forcedPath === null || forcedPath === 'synchron') && (
              <button
                type="button"
                role="radio"
                aria-checked={path === 'synchron'}
                onClick={() => setPath('synchron')}
                className={`rounded-xl border p-4 text-left transition ${
                  path === 'synchron'
                    ? 'border-neutral-900 bg-neutral-900 text-white'
                    : 'border-neutral-200 bg-white hover:border-neutral-400'
                }`}
              >
                <p className="font-semibold">I need to buy permits</p>
                <p className={`mt-1 text-xs ${path === 'synchron' ? 'text-neutral-300' : 'text-neutral-500'}`}>
                  Send a permit request to our trusted partner Synchron Permits
                </p>
              </button>
            )}
          </div>
          {forcedPath === 'synchron' && (
            <p className="mt-2 text-[11px] text-neutral-500">
              {brokerName} requires permits for this lane to be processed by our trusted partner
              Synchron Permits.
            </p>
          )}
          {forcedPath === 'upload' && (
            <p className="mt-2 text-[11px] text-neutral-500">
              {brokerName} asks carriers to upload their own permits for this lane.
            </p>
          )}

          {path === 'upload' && (
            <div className="mt-4 space-y-2">
              <Label>Permit files (you can also add more later)</Label>
              <label className="flex cursor-pointer flex-col items-center gap-1.5 rounded-xl border-2 border-dashed border-neutral-300 bg-neutral-50 px-4 py-6 text-center transition hover:border-neutral-500">
                <span className="text-sm font-medium">
                  {permitNames.length > 0
                    ? `${permitNames.length} file(s): ${permitNames.join(', ')}`
                    : 'Drag & drop or tap to choose permit files'}
                </span>
                <span className="text-xs text-neutral-500">One file per state is typical</span>
                <input
                  type="file"
                  name="permits"
                  multiple
                  accept=".pdf,.jpg,.jpeg,.png,.docx"
                  className="hidden"
                  onChange={(e) =>
                    setPermitNames(Array.from(e.target.files ?? []).map((f) => f.name))
                  }
                />
              </label>
            </div>
          )}
          {path === 'synchron' && (
            <div className="mt-4 space-y-2">
              <p className="rounded-lg bg-amber-50 p-3 text-xs leading-relaxed text-amber-800">
                Your request will be sent to our trusted partner Synchron Permits with your rate confirmation. The trip
                stays in <strong>Waiting for Permits</strong> until permits are added.
              </p>
              <p className="rounded-lg bg-green-50 p-3 text-xs leading-relaxed text-green-800">
                Permits processed by Synchron Permits include route support by default — no
                separate Google Maps route purchase is required for those permits.
              </p>
              {paymentDefault && (
                <p className="rounded-lg bg-neutral-50 p-3 text-xs leading-relaxed text-neutral-600">
                  {paymentDefault === 'broker'
                    ? `${brokerName} pays Synchron Permits for permit processing on this load.`
                    : 'The carrier is responsible for paying Synchron Permits for permit processing on this load.'}
                </p>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      <Button type="submit" className="w-full" size="lg" disabled={submitting}>
        {submitting
          ? 'Submitting…'
          : path === 'upload'
            ? 'Submit & upload permits'
            : 'Submit permit request'}
      </Button>
    </form>
  )
}
