'use client'

import { useActionState, useState } from 'react'
import { addLocation } from './actions'

const inputCls =
  'flex h-11 w-full rounded-lg border border-input bg-background px-3 py-2 text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'

interface Props {
  locations: { id: string; path: string }[]
  defaultParentId?: string | null
  trigger: React.ReactNode
}

export function AddLocationDialog({ locations, defaultParentId = null, trigger }: Props) {
  const [open, setOpen] = useState(false)
  const [state, formAction, pending] = useActionState(addLocation, null)

  // When the server action returns { ok: true }, close the dialog on the next
  // render. Doing this inline avoids the cascading-render trap of setState
  // inside useEffect.
  if (state && 'ok' in state && state.ok && open) {
    queueMicrotask(() => setOpen(false))
  }

  return (
    <>
      <span onClick={() => setOpen(true)}>{trigger}</span>
      {open && (
        <div
          className="fixed inset-0 z-50 bg-black/40 flex items-end sm:items-center justify-center p-4"
          onClick={() => setOpen(false)}
        >
          <div
            className="w-full max-w-md bg-background rounded-xl border p-4 space-y-4"
            onClick={e => e.stopPropagation()}
          >
            <h2 className="text-lg font-semibold">Add location</h2>
            <form action={formAction} className="space-y-3">
              {state && 'error' in state && state.error && (
                <div className="bg-destructive/10 text-destructive text-sm rounded-lg px-3 py-2 border border-destructive/20">
                  {state.error}
                </div>
              )}
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Name</label>
                <input name="name" type="text" required autoFocus className={inputCls} />
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Parent</label>
                <select name="parentId" defaultValue={defaultParentId ?? ''} className={inputCls}>
                  <option value="">— Top level —</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-sm font-medium">Notes</label>
                <textarea name="notes" rows={2} className={inputCls + ' h-auto min-h-[2.75rem]'} />
              </div>
              <div className="flex gap-2 pt-2">
                <button
                  type="button"
                  onClick={() => setOpen(false)}
                  className="flex-1 h-11 rounded-lg border bg-card text-sm font-medium"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={pending}
                  className="flex-1 h-11 rounded-lg bg-primary text-primary-foreground text-sm font-medium disabled:opacity-50"
                >
                  {pending ? 'Adding…' : 'Add'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  )
}
