'use client'

import { useRef, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'

/**
 * Drag-and-drop document upload (Nash, 2026-10-01): "It would have been
 * better to have a drag and drop… when you click on the drag and drop, it's
 * going to open the browse… the doc upload section should be available for
 * the next action."
 *
 * This component only collects files. The moment "Upload" is pressed it hands
 * them to `onUpload` and empties itself, so the next batch can be dropped
 * while the first is still uploading and being read — the caller shows the
 * files in its list as "processing". One zone for every role's trip view.
 */
export const DOCUMENT_ACCEPT = '.pdf,.jpg,.jpeg,.png,.docx'
const ACCEPT_EXT = /\.(pdf|jpe?g|png|docx)$/i

export function DocumentDropZone({
  kinds,
  kind,
  onKindChange,
  onUpload,
  single = false,
  disabled = false,
  children,
}: {
  /** Document type value → label. */
  kinds: Record<string, string>
  kind: string
  onKindChange: (kind: string) => void
  /** Called with the staged files; the zone is cleared at once. */
  onUpload: (files: File[], kind: string) => void
  /** One file only (a trip has one rate confirmation). */
  single?: boolean
  disabled?: boolean
  /** Notes shown under the zone. */
  children?: React.ReactNode
}) {
  const inputRef = useRef<HTMLInputElement>(null)
  const [staged, setStaged] = useState<File[]>([])
  const [dragOver, setDragOver] = useState(false)
  const [rejected, setRejected] = useState<string | null>(null)

  function add(list: FileList | File[] | null) {
    const incoming = [...(list ?? [])]
    if (incoming.length === 0) return
    const ok = incoming.filter((f) => ACCEPT_EXT.test(f.name))
    const bad = incoming.filter((f) => !ACCEPT_EXT.test(f.name))
    setRejected(bad.length ? `${bad.map((f) => f.name).join(', ')} — use a PDF, JPG, PNG or DOCX file.` : null)
    setStaged((current) => {
      if (single) return ok.slice(0, 1).length ? ok.slice(0, 1) : current
      const seen = new Set(current.map((f) => `${f.name}:${f.size}`))
      return [...current, ...ok.filter((f) => !seen.has(`${f.name}:${f.size}`))]
    })
  }

  function submit() {
    if (staged.length === 0) return
    const files = staged
    setStaged([])
    setRejected(null)
    if (inputRef.current) inputRef.current.value = ''
    onUpload(files, kind)
  }

  const kindLabel = kinds[kind] ?? 'document'
  return (
    <div className="space-y-3">
      <div className="flex flex-wrap items-end gap-3">
        <div className="min-w-40 space-y-2">
          <Label htmlFor="doc-kind">Document type</Label>
          <select
            id="doc-kind"
            value={kind}
            onChange={(e) => { onKindChange(e.target.value); setStaged([]) }}
            className="w-full rounded-lg border px-3 py-2 text-sm"
          >
            {Object.entries(kinds).map(([v, l]) => (
              <option key={v} value={v}>{l}</option>
            ))}
          </select>
        </div>
      </div>

      <label
        onDragOver={(e) => { e.preventDefault(); if (!disabled) setDragOver(true) }}
        onDragLeave={() => setDragOver(false)}
        onDrop={(e) => {
          e.preventDefault()
          setDragOver(false)
          if (!disabled) add(e.dataTransfer.files)
        }}
        className={`block cursor-pointer rounded-xl border-2 border-dashed p-6 text-center text-sm transition ${
          dragOver
            ? 'border-[#f5a623] bg-amber-50'
            : staged.length > 0
              ? 'border-green-300 bg-green-50/50'
              : 'border-neutral-300 hover:border-neutral-400'
        } ${disabled ? 'pointer-events-none opacity-60' : ''}`}
      >
        {staged.length > 0 ? (
          <span className="font-semibold text-green-700">
            ✓ {staged.length} file{staged.length === 1 ? '' : 's'} ready{single ? '' : ' — drop more or click to add'}
          </span>
        ) : (
          <>
            <span className="font-semibold">
              Drag &amp; drop {single ? `the ${kindLabel.toLowerCase()}` : `your ${kindLabel.toLowerCase()}s`} here
            </span>
            <span className="mt-1 block text-xs text-neutral-500">
              or click to browse{single ? '' : ' · several files at once is fine'} · PDF, JPG, PNG or DOCX
            </span>
          </>
        )}
        <input
          ref={inputRef}
          type="file"
          className="hidden"
          multiple={!single}
          accept={DOCUMENT_ACCEPT}
          disabled={disabled}
          onChange={(e) => { add(e.target.files); e.target.value = '' }}
        />
      </label>

      {rejected && <p className="text-xs text-red-600">{rejected}</p>}

      {staged.length > 0 && (
        <>
          <ul className="space-y-1">
            {staged.map((f, i) => (
              <li key={`${f.name}-${f.size}-${i}`} className="flex items-center justify-between gap-2 rounded-lg border bg-white px-3 py-1.5 text-xs">
                <span className="min-w-0 truncate">{f.name}</span>
                <button
                  type="button"
                  onClick={() => setStaged((list) => list.filter((_, j) => j !== i))}
                  className="shrink-0 text-neutral-400 transition hover:text-red-600"
                  title={`Remove ${f.name}`}
                  aria-label={`Remove ${f.name}`}
                >
                  ✕
                </button>
              </li>
            ))}
          </ul>
          <Button type="button" onClick={submit} className="w-full">
            Upload {staged.length} {kindLabel.toLowerCase()}{staged.length === 1 ? '' : 's'}
          </Button>
        </>
      )}
      {children}
    </div>
  )
}

/** A file on its way: uploading, or uploaded and being read. No state name yet. */
export function ProcessingFileRow({ name, label, failed = false, stalled = false, busy = false, onDismiss, onCancel, onRetry }: {
  name: string; label: string; failed?: boolean; stalled?: boolean; busy?: boolean
  onDismiss?: () => void; onCancel?: () => void; onRetry?: () => void
}) {
  return (
    <div className={`flex items-center justify-between gap-3 rounded-xl border p-3 ${failed ? 'border-red-200 bg-red-50/50' : stalled ? 'border-amber-200 bg-amber-50/50' : 'border-blue-200 bg-blue-50/50'}`}>
      <div className="min-w-0">
        <p className="truncate text-sm font-semibold">{name}</p>
        <p className={`text-xs ${failed ? 'text-red-700' : stalled ? 'text-amber-800' : 'text-blue-800'}`}>{label}</p>
      </div>
      {failed ? (
        <span className="flex shrink-0 items-center gap-3">
          {onRetry && <button type="button" disabled={busy} onClick={onRetry} className="text-xs font-semibold text-blue-700 hover:underline disabled:opacity-50">{busy ? 'Queuing…' : 'Retry'}</button>}
          {onDismiss && <button type="button" onClick={onDismiss} className="text-xs font-semibold text-neutral-500 hover:text-neutral-800">Dismiss</button>}
        </span>
      ) : (
        <span className="flex shrink-0 items-center gap-3">
          {onCancel && <button type="button" disabled={busy} onClick={onCancel} className="text-xs font-semibold text-red-700 hover:underline disabled:opacity-50">{busy ? 'Stopping…' : 'Cancel'}</button>}
          {!stalled && <span className="h-4 w-4 animate-spin rounded-full border-2 border-blue-300 border-t-blue-700" aria-hidden />}
        </span>
      )}
    </div>
  )
}
