'use client'

import { useRef, useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import { X, ImagePlus } from 'lucide-react'
import { createMap } from './actions'

interface LocOption {
  id: string
  path: string
}

export function NewMapDialog({
  locations,
  trigger,
  presetLocationId,
  presetLocationPath,
}: {
  locations: LocOption[]
  trigger: React.ReactNode
  presetLocationId?: string
  presetLocationPath?: string
}) {
  const [open, setOpen] = useState(false)
  const [name, setName] = useState('')
  const [locationId, setLocationId] = useState(presetLocationId || '')
  const [file, setFile] = useState<File | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [pending, startTransition] = useTransition()
  const fileRef = useRef<HTMLInputElement>(null)
  const router = useRouter()

  const close = () => {
    setOpen(false)
    setName('')
    setLocationId(presetLocationId || '')
    setFile(null)
    setError(null)
    if (fileRef.current) fileRef.current.value = ''
  }

  const submit = () => {
    setError(null)
    if (!name.trim()) {
      setError('Name is required')
      return
    }
    if (!locationId) {
      setError('Pick a location')
      return
    }
    if (!file) {
      setError('Pick an image')
      return
    }
    const fd = new FormData()
    fd.set('name', name.trim())
    fd.set('locationId', locationId)
    fd.set('image', file)
    startTransition(async () => {
      const res = await createMap(fd)
      if (!res.ok) {
        setError(res.error)
        return
      }
      close()
      router.push(`/locations/maps/${res.id}`)
    })
  }

  return (
    <>
      <span onClick={() => setOpen(true)}>{trigger}</span>
      {open && (
        <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/40 p-4" onClick={close}>
          <div
            onClick={e => e.stopPropagation()}
            className="w-full max-w-md rounded-2xl bg-background border shadow-xl p-4 space-y-3"
          >
            <div className="flex items-center justify-between">
              <div className="font-medium">New map</div>
              <button
                type="button"
                onClick={close}
                aria-label="Close"
                className="text-muted-foreground hover:text-foreground"
              >
                <X className="size-4" />
              </button>
            </div>

            <div className="space-y-1.5">
              <label className="text-xs text-muted-foreground">Name</label>
              <input
                value={name}
                onChange={e => setName(e.target.value)}
                placeholder="Property aerial 2026"
                className="w-full h-10 rounded-lg border bg-background px-3 text-base outline-none focus:ring-2 focus:ring-ring"
              />
            </div>

            {presetLocationId ? (
              <div className="space-y-1.5">
                <label className="text-xs text-muted-foreground">
                  Map of
                </label>
                <div className="w-full h-10 rounded-lg border bg-muted/40 px-3 flex items-center text-sm text-muted-foreground truncate">
                  {presetLocationPath}
                </div>
              </div>
            ) : (
              <div className="space-y-1.5">
                <label className="text-xs text-muted-foreground">
                  Map of
                </label>
                <select
                  value={locationId}
                  onChange={e => setLocationId(e.target.value)}
                  className="w-full h-10 rounded-lg border bg-background px-3 text-base outline-none focus:ring-2 focus:ring-ring"
                >
                  <option value="" disabled>Choose a location…</option>
                  {locations.map(l => (
                    <option key={l.id} value={l.id}>
                      {l.path}
                    </option>
                  ))}
                </select>
              </div>
            )}

            <div className="space-y-1.5">
              <label className="text-xs text-muted-foreground">Image</label>
              <button
                type="button"
                onClick={() => fileRef.current?.click()}
                className="w-full h-24 rounded-lg border-2 border-dashed bg-muted/30 flex items-center justify-center gap-2 text-sm text-muted-foreground"
              >
                <ImagePlus className="size-5" />
                {file ? file.name : 'Choose image'}
              </button>
              <input
                ref={fileRef}
                type="file"
                accept="image/*"
                className="sr-only"
                onChange={e => setFile(e.target.files?.[0] || null)}
              />
            </div>

            {error && <div className="text-xs text-rose-600">{error}</div>}

            <div className="flex justify-end gap-2">
              <button
                type="button"
                onClick={close}
                disabled={pending}
                className="h-10 px-3 rounded-lg border text-sm"
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={submit}
                disabled={pending}
                className="h-10 px-4 rounded-lg bg-primary text-primary-foreground text-sm font-medium disabled:opacity-50"
              >
                {pending ? 'Uploading…' : 'Create'}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
