'use client'

import { useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
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'

/**
 * Broker "Create Trip Request" — intake-page style (Task 15) + the Permit
 * Handling decision per the order-intake workflow doc (Tasks 43-46):
 * two option cards, a REQUIRED payment-responsibility choice for the Synchron
 * flow, the routes-included notice, and workflow-specific confirmations.
 * Emails to the dispatcher/Synchron are the email backend (later) — the
 * secure invite link is shown for direct sharing meanwhile.
 */

type Policy = 'synchron_required' | 'upload_allowed' | ''
type PayParty = 'broker' | 'carrier' | ''

interface Result {
  refCode: string
  inviteUrl: string | null
  policy: Exclude<Policy, ''>
  paymentParty: PayParty
}

import { ContactPicker } from '@/components/app/contact-picker'
import type { CarrierContact } from '@/types/db'

export function BrokerRequestForm({ slug,
  defaultPolicy = 'ask',
  defaultPayment = 'ask',
  dispatchers = [],
}: {
slug: string
  /** Broker defaults (§22): preselect the cards; a hard default LOCKS the choice. */
  defaultPolicy?: 'synchron_required' | 'upload_allowed' | 'ask'
  defaultPayment?: 'broker' | 'carrier' | 'ask'
  /** The broker's saved carrier dispatchers (2026-09-13). */
  dispatchers?: CarrierContact[]
}) {
  const router = useRouter()
  const policyLocked = defaultPolicy !== 'ask'
  const [rateCon, setRateCon] = useState<File | null>(null)
  const [policy, setPolicy] = useState<Policy>(defaultPolicy === 'ask' ? '' : defaultPolicy)
  const [paymentParty, setPaymentParty] = useState<PayParty>(
    defaultPayment === 'ask' ? '' : defaultPayment,
  )
  const [pending, setPending] = useState(false)
  const [dragOver, setDragOver] = useState(false)
  const formRef = useRef<HTMLFormElement>(null)
  /** Fill the dispatch fields from a saved contact; everything stays editable. */
  function fillFrom(c: { name: string; email: string; phone: string; phone_ext: string }) {
    const form = formRef.current
    if (!form) return
    const set = (field: string, value: string) => {
      const el = form.elements.namedItem(field) as HTMLInputElement | null
      if (el) el.value = value
    }
    set('contact_name', c.name)
    set('contact_email', c.email)
    set('contact_phone', c.phone)
    set('contact_phone_ext', c.phone_ext)
  }
  /** Remember the dispatcher for next time so the contact list builds itself. */
  async function rememberDispatcher(fd: FormData) {
    const email = String(fd.get('contact_email') ?? '').trim()
    if (!email || dispatchers.some((d) => d.email.toLowerCase() === email.toLowerCase())) return
    try {
      await fetch('/api/contacts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          op: 'add',
          role: 'dispatcher',
          name: String(fd.get('contact_name') ?? ''),
          email,
          phone: String(fd.get('contact_phone') ?? ''),
          phone_ext: String(fd.get('contact_phone_ext') ?? ''),
        }),
      })
    } catch {
      // best effort — the request itself already went through
    }
  }
  const [result, setResult] = useState<Result | null>(null)

  async function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (!rateCon) {
      toast.error('Drag and drop the rate confirmation first.')
      return
    }
    if (!policy) {
      toast.error('Choose how permits should be handled for this trip.')
      return
    }
    if (policy === 'synchron_required' && !paymentParty) {
      toast.error('Choose who will pay Synchron Permits for this permit order.')
      return
    }
    setPending(true)
    try {
      const form = e.currentTarget
      const source = new FormData(form)
      const fd = new FormData()
      fd.set('slug', slug)
      fd.set('rate_confirmation', rateCon)
      fd.set('carrier_company', String(source.get('carrier_company') ?? ''))
      fd.set('contact_name', String(source.get('contact_name') ?? ''))
      fd.set('contact_email', String(source.get('contact_email') ?? ''))
      fd.set('contact_phone', String(source.get('contact_phone') ?? ''))
      fd.set('contact_phone_ext', String(source.get('contact_phone_ext') ?? ''))
      fd.set('notes', String(source.get('notes') ?? ''))
      fd.set('permit_policy', policy)
      if (policy === 'synchron_required' && paymentParty) {
        fd.set('payment_responsible_party', paymentParty)
      }
      // the carrier-facing path mirrors the broker's decision
      fd.set('permit_source', policy === 'synchron_required' ? 'synchron' : 'upload')

      const res = await fetch('/api/intake', { method: 'POST', body: fd })
      const json = await res.json()
      if (!res.ok) {
        toast.error(json.error ?? 'Could not create the trip request.')
        return
      }
      void rememberDispatcher(fd)
      if (json.invite_url) {
        try {
          await navigator.clipboard.writeText(json.invite_url)
          toast.info('Dispatcher invite link copied to your clipboard')
        } catch {
          // clipboard unavailable — the link is shown on the confirmation
        }
      }
      setResult({
        refCode: json.trip_ref,
        inviteUrl: json.invite_url ?? null,
        policy,
        paymentParty,
      })
      router.refresh()
    } finally {
      setPending(false)
    }
  }

  // Workflow-specific confirmation (source doc §9) — reinforces what happened.
  if (result) {
    const synchron = result.policy === 'synchron_required'
    return (
      <Card className="mt-6">
        <CardContent className="space-y-4 pt-6">
          <p className="text-sm font-bold text-green-700">
            ✓ Trip request {result.refCode} created
          </p>
          {synchron ? (
            <ul className="space-y-1.5 text-sm text-neutral-700">
              <li>Your permit request has been sent to Synchron Permits.</li>
              <li>The carrier dispatcher has been included for coordination.</li>
              <li>Synchron Permits will begin the intake process.</li>
              <li>
                Payment responsibility has been set to:{' '}
                <span className="font-semibold capitalize">{result.paymentParty} pays</span>.
              </li>
              <li>Permits will be uploaded into this workspace by Synchron once processed.</li>
              <li>
                Routes for each Synchron-processed permit are included and will be attached to
                this workspace.
              </li>
            </ul>
          ) : (
            <ul className="space-y-1.5 text-sm text-neutral-700">
              <li>Your trip has been created.</li>
              <li>The carrier dispatcher has been emailed a secure workspace link.</li>
              <li>The carrier is expected to upload existing permits.</li>
              <li>You will be notified when permits are uploaded.</li>
              <li>
                Routes are not included automatically, but they can be requested from the
                workspace if needed.
              </li>
            </ul>
          )}
          {result.inviteUrl && (
            <div className="rounded-lg bg-neutral-50 p-3 text-xs text-neutral-600">
              Secure dispatcher link (emails activate with the backend — share it directly
              meanwhile):{' '}
              <button
                className="font-mono font-semibold underline"
                onClick={() => {
                  navigator.clipboard.writeText(result.inviteUrl!)
                  toast.success('Link copied')
                }}
              >
                copy link
              </button>
            </div>
          )}
          <Button onClick={() => router.push('/dashboard')} className="w-full">
            Go to dashboard
          </Button>
        </CardContent>
      </Card>
    )
  }

  return (
    <form ref={formRef} onSubmit={submit} className="mt-6 space-y-5">
      {/* Rate con — the anchor document, drag & drop like the intake page */}
      <Card>
        <CardContent className="pt-6">
          <Label>
            Rate confirmation <span className="text-red-600">*</span>
          </Label>
          <label
            onDragOver={(e) => {
              e.preventDefault()
              setDragOver(true)
            }}
            onDragLeave={() => setDragOver(false)}
            onDrop={(e) => {
              e.preventDefault()
              setDragOver(false)
              const f = e.dataTransfer.files?.[0]
              if (f) setRateCon(f)
            }}
            className={`mt-2 block cursor-pointer rounded-xl border-2 border-dashed p-8 text-center text-sm transition ${
              dragOver
                ? 'border-[#f5a623] bg-amber-50'
                : rateCon
                  ? 'border-green-300 bg-green-50/50'
                  : 'border-neutral-300 hover:border-neutral-400'
            }`}
          >
            {rateCon ? (
              <span className="font-semibold text-green-700">✓ {rateCon.name}</span>
            ) : (
              <>
                <span className="font-semibold">Drag &amp; drop the rate confirmation here</span>
                <span className="mt-1 block text-xs text-neutral-500">
                  or click to choose · PDF, JPG, PNG, DOCX · max 25MB
                </span>
              </>
            )}
            <input
              type="file"
              className="hidden"
              accept=".pdf,.jpg,.jpeg,.png,.docx"
              onChange={(e) => setRateCon(e.target.files?.[0] ?? null)}
            />
          </label>
        </CardContent>
      </Card>

      {/* Dispatch contact — same fields as the intake page. Nash, 2026-09-13:
          "He can choose any of the dispatchers from his contact list, or he can
          just type the dispatch name and the dispatch email and dispatch phone." */}
      <Card>
        <CardContent className="grid gap-4 pt-6 sm:grid-cols-2">
          <ContactPicker dispatchers={dispatchers} onPick={fillFrom} className="sm:col-span-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">
              Dispatch 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">
              Dispatch 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">
              Dispatch phone <span className="text-red-600">*</span>
            </Label>
            <div className="flex gap-2">
              <Input id="contact_phone" name="contact_phone" required className="flex-1" />
              <Input
                id="contact_phone_ext"
                name="contact_phone_ext"
                placeholder="Ext."
                title="Extension (optional)"
                className="w-20"
              />
            </div>
          </div>
          <div className="space-y-2 sm:col-span-2">
            <Label htmlFor="notes">Notes</Label>
            <Textarea
              id="notes"
              name="notes"
              rows={3}
              placeholder="Please start working on your permits for this order"
            />
          </div>
        </CardContent>
      </Card>

      {/* ===== Permit Handling (source doc §8): the broker's decision ===== */}
      <Card>
        <CardContent className="pt-6">
          <h3 className="text-sm font-bold uppercase tracking-wide text-neutral-500">
            Permit Handling
          </h3>
          <p className="mt-1 text-sm text-neutral-600">
            How should permits be handled for this trip? <span className="text-red-600">*</span>
          </p>
          <div className="mt-3 grid gap-3 sm:grid-cols-2">
            {/* Card 1: Carrier Will Upload Permits */}
            <button
              type="button"
              disabled={policyLocked && defaultPolicy !== 'upload_allowed'}
              onClick={() => {
                setPolicy('upload_allowed')
                setPaymentParty(defaultPayment === 'ask' ? '' : defaultPayment)
              }}
              className={`rounded-xl border-2 p-4 text-left transition disabled:cursor-not-allowed disabled:opacity-40 ${
                policy === 'upload_allowed'
                  ? 'border-[#0f1b2d] bg-[#0f1b2d] text-white'
                  : 'hover:border-neutral-400'
              }`}
            >
              <p className="text-sm font-bold">Carrier Will Upload Permits</p>
              <p className={`mt-1 text-xs ${policy === 'upload_allowed' ? 'text-neutral-300' : 'text-neutral-500'}`}>
                Use this option when the carrier already has permits or will provide permits from
                another source. HeavyHaul Agent will send the carrier dispatcher a workspace link
                to upload the permits.
              </p>
              <ul className={`mt-2 space-y-0.5 text-[11px] ${policy === 'upload_allowed' ? 'text-neutral-300' : 'text-neutral-500'}`}>
                <li>• Carrier dispatcher receives upload link</li>
                <li>• Trip status becomes Waiting on Carrier Permits</li>
                <li>• Synchron Permits is not notified as a new permit order</li>
                <li>• Routes are not included automatically</li>
                <li>• Routes can be requested or purchased separately if needed</li>
              </ul>
            </button>
            {/* Card 2: Request Permits From Synchron Permits */}
            <button
              type="button"
              disabled={policyLocked && defaultPolicy !== 'synchron_required'}
              onClick={() => setPolicy('synchron_required')}
              className={`rounded-xl border-2 p-4 text-left transition disabled:cursor-not-allowed disabled:opacity-40 ${
                policy === 'synchron_required'
                  ? 'border-[#0f1b2d] bg-[#0f1b2d] text-white'
                  : 'hover:border-neutral-400'
              }`}
            >
              <p className="text-sm font-bold">Request Permits From Synchron Permits</p>
              <p className={`mt-1 text-xs ${policy === 'synchron_required' ? 'text-neutral-300' : 'text-neutral-500'}`}>
                Use this option when you want Synchron Permits to process the permits for this
                trip. HeavyHaul Agent will notify Synchron Permits and the carrier dispatcher with
                the rate confirmation and order details.
              </p>
              <ul className={`mt-2 space-y-0.5 text-[11px] ${policy === 'synchron_required' ? 'text-neutral-300' : 'text-neutral-500'}`}>
                <li>• Synchron Permits receives the order request</li>
                <li>• Carrier dispatcher receives a coordination email</li>
                <li>• Trip status becomes Synchron Permits Processing</li>
                <li>• Permit uploads are handled by Synchron through API</li>
                <li>• Routes are included for every permit processed by Synchron</li>
                <li>• Manual permit upload is disabled for broker and carrier</li>
                <li>• You choose who is responsible for payment</li>
              </ul>
            </button>
          </div>

          {policyLocked && (
            <p className="mt-2 text-[11px] text-neutral-400">
              Set by your intake defaults — change them in Settings → Permit handling defaults.
            </p>
          )}

          {/* Payment responsibility — REQUIRED for the Synchron flow (§8) */}
          {policy === 'synchron_required' && (
            <div className="mt-4 rounded-xl border p-4">
              <p className="text-sm font-semibold">
                Who will pay Synchron Permits for this permit order?{' '}
                <span className="text-red-600">*</span>
              </p>
              <div className="mt-3 grid gap-3 sm:grid-cols-2">
                <button
                  type="button"
                  onClick={() => setPaymentParty('broker')}
                  className={`rounded-lg border-2 p-3 text-left transition ${
                    paymentParty === 'broker'
                      ? 'border-[#f5a623] bg-amber-50'
                      : 'hover:border-neutral-400'
                  }`}
                >
                  <p className="text-sm font-bold">Broker pays</p>
                  <p className="mt-0.5 text-xs text-neutral-500">
                    The broker is responsible for permit processing fees for this order.
                  </p>
                </button>
                <button
                  type="button"
                  onClick={() => setPaymentParty('carrier')}
                  className={`rounded-lg border-2 p-3 text-left transition ${
                    paymentParty === 'carrier'
                      ? 'border-[#f5a623] bg-amber-50'
                      : 'hover:border-neutral-400'
                  }`}
                >
                  <p className="text-sm font-bold">Carrier pays</p>
                  <p className="mt-0.5 text-xs text-neutral-500">
                    The carrier is responsible for permit processing fees for this order. Synchron
                    Permits and the carrier dispatcher will be notified.
                  </p>
                </button>
              </div>
              {/* Routes-included notice — visible BEFORE submission (§8) */}
              <div className="mt-3 rounded-lg bg-green-50 p-3 text-xs text-green-800">
                <span className="font-bold">Routes are included.</span> When Synchron Permits
                processes the permits, the route for each processed permit will be included and
                attached to the HeavyHaul Agent workspace. No separate Google Maps route purchase
                is required for those permits.
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      <Button type="submit" className="w-full" disabled={pending}>
        {pending ? 'Creating trip request…' : 'Create trip request & invite dispatcher'}
      </Button>
    </form>
  )
}
