'use client'

import { useState, useTransition } from 'react'
import { Pencil, Trash2 } from 'lucide-react'
import {
  renameLocationAction,
  moveLocationAction,
  deleteLocationAction,
} 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 {
  id: string
  name: string
  parentId: string | null
  locations: { id: string; path: string }[]
}

export function LocationActions({ id, name, parentId, locations }: Props) {
  const [open, setOpen] = useState(false)
  const [pending, startTransition] = useTransition()
  const [error, setError] = useState<string | null>(null)

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="inline-flex items-center gap-1 h-10 px-3 rounded-lg border bg-card text-sm font-medium"
      >
        <Pencil className="size-4" />
      </button>
      {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-3"
            onClick={e => e.stopPropagation()}
          >
            <h2 className="text-lg font-semibold">Edit location</h2>
            {error && (
              <div className="bg-destructive/10 text-destructive text-sm rounded-lg px-3 py-2 border border-destructive/20">
                {error}
              </div>
            )}
            <form
              action={async (fd) => {
                const newName = (fd.get('name') as string)?.trim()
                if (!newName) return
                startTransition(async () => {
                  try {
                    setError(null)
                    await renameLocationAction(id, newName)
                    setOpen(false)
                  } catch (e) {
                    setError(e instanceof Error ? e.message : 'Could not rename')
                  }
                })
              }}
              className="space-y-3"
            >
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Name</label>
                <input name="name" defaultValue={name} className={inputCls} required />
              </div>
              <button
                type="submit"
                disabled={pending}
                className="w-full h-11 rounded-lg bg-primary text-primary-foreground text-sm font-medium disabled:opacity-50"
              >
                Rename
              </button>
            </form>

            <form
              action={async (fd) => {
                const newParent = (fd.get('parentId') as string) || null
                startTransition(async () => {
                  try {
                    setError(null)
                    await moveLocationAction(id, newParent)
                    setOpen(false)
                  } catch (e) {
                    setError(e instanceof Error ? e.message : 'Could not move')
                  }
                })
              }}
              className="space-y-3 pt-2 border-t"
            >
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Move under</label>
                <select name="parentId" defaultValue={parentId ?? ''} className={inputCls}>
                  <option value="">— Top level —</option>
                  {locations.map(l => (
                    <option key={l.id} value={l.id}>{l.path}</option>
                  ))}
                </select>
              </div>
              <button
                type="submit"
                disabled={pending}
                className="w-full h-11 rounded-lg border bg-card text-sm font-medium disabled:opacity-50"
              >
                Move
              </button>
            </form>

            <button
              type="button"
              disabled={pending}
              onClick={() => {
                if (!confirm('Delete this location? It must be empty.')) return
                startTransition(async () => {
                  const res = await deleteLocationAction(id)
                  if (res && 'error' in res && res.error) setError(res.error)
                })
              }}
              className="w-full h-11 rounded-lg border bg-card text-destructive text-sm font-medium hover:bg-destructive/10 disabled:opacity-50 inline-flex items-center justify-center gap-2"
            >
              <Trash2 className="size-4" /> Delete location
            </button>

            <button
              type="button"
              onClick={() => setOpen(false)}
              className="w-full h-11 rounded-lg text-sm font-medium text-muted-foreground"
            >
              Close
            </button>
          </div>
        </div>
      )}
    </>
  )
}
