'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Label } from '@/components/ui/label'

/**
 * Freight Broker · New Trip — `/fb-new-trip` (Nash, 2026-09-19): two sections only.
 *
 *   1. Drag & drop the rate confirmation (required — it creates the trip)
 *   2. Drag & drop existing permits (optional, any number)
 *   → Create trip
 *
 * Inviting the carrier dispatcher and choosing permit handling (carrier
 * uploads vs. request from Synchron Permits) are NOT part of creating the
 * trip any more — "he can do it once the order is created", from the
 * workspace's People tab and the permit-handling choice. A broker may also
 * create a trip that is already finished, just to analyze it.
 */

const ACCEPT = '.pdf,.jpg,.jpeg,.png,.docx'
const ALLOWED = new Set(['application/pdf', 'image/jpeg', 'image/png', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'])
const MAX = 25 * 1024 * 1024
const okFile = (f: File) => f.size > 0 && f.size <= MAX && ALLOWED.has(f.type)

interface Result { tripId: string; refCode: string; permitsUploaded: number; permitsFailed: string[]; extracted: boolean }

export function NewTripForm() {
  const router = useRouter()
  const [rateCon, setRateCon] = useState<File | null>(null)
  const [permits, setPermits] = useState<File[]>([])
  const [pending, setPending] = useState<string | null>(null)
  const [result, setResult] = useState<Result | null>(null)

  function addPermits(files: FileList | File[] | null) {
    if (!files) return
    const list = [...files]
    const bad = list.filter((f) => !okFile(f))
    if (bad.length) toast.error(`${bad.length} file${bad.length === 1 ? '' : 's'} skipped — PDF, JPG, PNG or DOCX up to 25MB.`)
    setPermits((cur) => {
      const seen = new Set(cur.map((f) => `${f.name}:${f.size}`))
      return [...cur, ...list.filter((f) => okFile(f) && !seen.has(`${f.name}:${f.size}`))]
    })
  }

  async function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (!rateCon) return void toast.error('Drag and drop the rate confirmation first.')
    if (!okFile(rateCon)) return void toast.error('The rate confirmation must be a PDF, JPG, PNG or DOCX up to 25MB.')
    setPending('Creating the trip…')
    try {
      const fd = new FormData()
      fd.set('rate_confirmation', rateCon)
      const res = await fetch('/api/fb/new-trip', { method: 'POST', body: fd })
      const json = await res.json().catch(() => ({}))
      if (!res.ok) return void toast.error(json.error ?? 'Could not create the trip.')
      const failed: string[] = []
      let uploaded = 0
      for (const [i, file] of permits.entries()) {
        setPending(`Uploading permit ${i + 1} of ${permits.length}…`)
        const pf = new FormData()
        pf.set('file', file)
        pf.set('kind', 'permit')
        const r = await fetch(`/api/trips/${json.trip_id}/documents`, { method: 'POST', body: pf })
        if (r.ok) uploaded++
        else failed.push(file.name)
      }
      setResult({ tripId: json.trip_id, refCode: json.trip_ref, permitsUploaded: uploaded, permitsFailed: failed, extracted: !!json.extracted })
      router.refresh()
    } finally {
      setPending(null)
    }
  }

  if (result) {
    return (
      <Card className="mt-6">
        <CardContent className="space-y-4 pt-6">
          <p className="text-sm font-bold text-green-700">✓ Trip {result.refCode} created</p>
          <ul className="space-y-1.5 text-sm text-neutral-700">
            <li>Rate confirmation saved{result.extracted ? ' — lane, commodity and dimensions were read from it.' : '. Fill in the lane and commodity in the workspace if they are blank.'}</li>
            <li>
              {result.permitsUploaded > 0
                ? `${result.permitsUploaded} permit${result.permitsUploaded === 1 ? '' : 's'} uploaded — states, dates and warnings are being read.`
                : 'No permits uploaded yet — add them any time from the workspace.'}
            </li>
            {result.permitsFailed.length > 0 && <li className="text-red-700">Could not upload: {result.permitsFailed.join(', ')}. Try again from the workspace.</li>}
            <li>Next, when you are ready: invite the carrier dispatcher from the People tab, and choose whether the carrier uploads permits or you request them from Synchron Permits.</li>
          </ul>
          <div className="flex flex-col gap-2 sm:flex-row">
            <Button asChild className="flex-1"><Link href={`/fb-trip-workspace/${result.refCode}`}>Open trip workspace</Link></Button>
            <Button variant="outline" onClick={() => router.push('/fb-dashboard')} className="flex-1">Go to dashboard</Button>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <form onSubmit={submit} className="mt-6 space-y-5">
      {/* 1 — Rate confirmation */}
      <Card>
        <CardContent className="pt-6">
          <p className="text-[11px] font-bold uppercase tracking-wide text-neutral-400">Step 1</p>
          <Label className="mt-1 block text-base">Rate confirmation <span className="text-red-600">*</span></Label>
          <DropZone
            file={rateCon}
            onFiles={(files) => setRateCon(files?.[0] ?? null)}
            idle={<><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></>}
          />
        </CardContent>
      </Card>

      {/* 2 — Permits */}
      <Card>
        <CardContent className="pt-6">
          <p className="text-[11px] font-bold uppercase tracking-wide text-neutral-400">Step 2</p>
          <Label className="mt-1 block text-base">Permits <span className="text-xs font-normal text-neutral-500">(optional — if you already have them)</span></Label>
          <DropZone
            multiple
            file={null}
            onFiles={addPermits}
            idle={<><span className="font-semibold">Drag &amp; drop all the permits here</span><span className="mt-1 block text-xs text-neutral-500">or click to choose · as many as you have · PDF, JPG, PNG, DOCX · max 25MB each</span></>}
          />
          {permits.length > 0 && (
            <ul className="mt-3 space-y-1.5 text-sm">
              {permits.map((f) => (
                <li key={`${f.name}:${f.size}`} className="flex items-center justify-between rounded-lg bg-neutral-50 px-3 py-2">
                  <span className="truncate font-medium text-green-700">✓ {f.name}</span>
                  <button type="button" onClick={() => setPermits((cur) => cur.filter((x) => x !== f))} className="ml-3 text-xs font-bold text-neutral-500 hover:text-red-600">Remove</button>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>

      <Button type="submit" size="lg" className="w-full" disabled={!!pending || !rateCon}>
        {pending ?? (permits.length > 0 ? `Create trip with ${permits.length} permit${permits.length === 1 ? '' : 's'}` : 'Create trip')}
      </Button>
      <p className="text-center text-xs text-neutral-500">You can invite the carrier dispatcher and decide how permits are handled after the trip is created.</p>
    </form>
  )
}

function DropZone({ file, multiple, onFiles, idle }: { file: File | null; multiple?: boolean; onFiles: (files: FileList | null) => void; idle: React.ReactNode }) {
  const [over, setOver] = useState(false)
  return (
    <label
      onDragOver={(e) => { e.preventDefault(); setOver(true) }}
      onDragLeave={() => setOver(false)}
      onDrop={(e) => { e.preventDefault(); setOver(false); onFiles(e.dataTransfer.files) }}
      className={`mt-2 block cursor-pointer rounded-xl border-2 border-dashed p-8 text-center text-sm transition ${
        over ? 'border-[#f5a623] bg-amber-50' : file ? 'border-green-300 bg-green-50/50' : 'border-neutral-300 hover:border-neutral-400'
      }`}
    >
      {file ? <span className="font-semibold text-green-700">✓ {file.name}</span> : idle}
      <input type="file" className="hidden" accept={ACCEPT} multiple={multiple} onChange={(e) => { onFiles(e.target.files); e.target.value = '' }} />
    </label>
  )
}
