"use client"

import { useEffect, useMemo, useState } from "react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { FieldGroup, Field, FieldLabel } from "@/components/ui/field"
import { Spinner } from "@/components/ui/spinner"
import { toast } from "sonner"
import type { LocationRow } from "@/lib/locations/tree"

interface LocationDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  location: LocationRow | null
  allLocations: LocationRow[]
  onSaved: () => void
}

export function LocationDialog({ open, onOpenChange, location, allLocations, onSaved }: LocationDialogProps) {
  const [loading, setLoading] = useState(false)
  const [value, setValue] = useState("")
  const [parentId, setParentId] = useState<string>("root")

  const sortedLocations = useMemo(
    () =>
      [...allLocations]
        .filter((l) => l.id !== location?.id)
        .sort((a, b) => a.path.join(" > ").localeCompare(b.path.join(" > "), "es")),
    [allLocations, location],
  )

  useEffect(() => {
    if (!open) return
    if (location) {
      setValue(location.value)
      setParentId(location.parent_id ?? "root")
    } else {
      setValue("")
      setParentId("root")
    }
  }, [open, location])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const trimmed = value.trim()
    if (!trimmed) {
      toast.error("Ingresa un nombre de ubicación")
      return
    }

    setLoading(true)

    if (location) {
      const response = await fetch(`/api/locations/${location.id}`, {
        method: "PATCH",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          value: trimmed,
          parentId: parentId === "root" ? null : parentId,
        }),
      })
      const payload = (await response.json().catch(() => null)) as { error?: string } | null

      if (!response.ok) {
        toast.error(payload?.error ?? "No se pudo editar ubicación")
        setLoading(false)
        return
      }

      toast.success("Ubicación editada")
    } else {
      const response = await fetch("/api/locations", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          value: trimmed,
          parentId: parentId === "root" ? null : parentId,
        }),
      })
      const payload = (await response.json().catch(() => null)) as { error?: string } | null

      if (!response.ok) {
        toast.error(payload?.error ?? "No se pudo crear ubicación")
        setLoading(false)
        return
      }

      toast.success("Ubicación creada")
    }

    setLoading(false)
    onOpenChange(false)
    onSaved()
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="rounded-[var(--ds-radius-l)] border-[var(--ds-neutral-200)] bg-white shadow-[var(--ds-shadow-8dp)] sm:max-w-[440px]">
        <DialogHeader>
          <DialogTitle className="ds-type-global-m ds-type-semibold text-[var(--ds-text-neutral-default)]">
            {location ? "Editar ubicación" : "Nueva ubicación"}
          </DialogTitle>
          <DialogDescription className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
            {location ? "Modifica los datos de la ubicación" : "Crea un nodo raíz o un hijo dentro del árbol"}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit}>
          <FieldGroup className="gap-[var(--ds-space-4x)] py-[var(--ds-space-4x)]">
            <Field>
              <FieldLabel className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Nombre
              </FieldLabel>
              <Input
                value={value}
                onChange={(e) => setValue(e.target.value)}
                placeholder="Ej: Argentina, Santiago, Piso 3"
                required
                className="h-10 rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] bg-white px-[var(--ds-space-2x)] ds-type-global-s text-[var(--ds-text-neutral-default)] placeholder:text-[var(--ds-text-neutral-lighter)] focus-visible:border-[var(--ds-brand-400)] focus-visible:ring-[var(--ds-brand-400)]/50"
              />
            </Field>

            <Field>
              <FieldLabel className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Ubicación padre
              </FieldLabel>
              <Select value={parentId} onValueChange={setParentId}>
                <SelectTrigger className="h-10 rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] bg-white px-[var(--ds-space-2x)] ds-type-global-xs text-[var(--ds-text-neutral-default)]">
                  <SelectValue placeholder="Nodo padre" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="root">Sin padre (nivel raíz)</SelectItem>
                  {sortedLocations.map((loc) => (
                    <SelectItem key={loc.id} value={loc.id}>
                      {"  ".repeat(loc.depth - 1) + loc.value}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </Field>
          </FieldGroup>

          <DialogFooter className="gap-[var(--ds-space-2x)]">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={loading}
              className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)] hover:bg-[var(--ds-neutral-100)]"
            >
              Cancelar
            </Button>
            <Button
              type="submit"
              disabled={loading}
              className="rounded-[var(--ds-radius-m)] bg-[var(--ds-brand-400)] ds-type-global-xs ds-type-semibold text-white hover:bg-[var(--ds-brand-500)]"
            >
              {loading && <Spinner className="mr-[var(--ds-space-2x)]" />}
              {location ? "Guardar cambios" : "Crear ubicación"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
