"use client"

import { useState, useEffect, useMemo } from "react"
import { useRouter } from "next/navigation"
import { createClient } from "@/lib/supabase/client"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Switch } from "@/components/ui/switch"
import { NumericInput } from "@/components/ui/numeric-input"
import { Spinner } from "@/components/ui/spinner"
import { X, ImageIcon } from "lucide-react"
import { toast } from "sonner"
import type { Database } from "@/lib/supabase/database.types"
import type { LocationRow } from "@/lib/locations/tree"
import { buildLocationChildrenMap, getLocationPathIds } from "@/lib/locations/tree"

type Resource = Database["public"]["Tables"]["resources"]["Row"]
type ResourceType = Database["public"]["Tables"]["resource_types"]["Row"]

interface ResourceFormProps {
  resource?: Resource | null
}

export function ResourceForm({ resource }: ResourceFormProps) {
  const router = useRouter()
  const supabase = useMemo(() => createClient(), [])
  const isEditing = !!resource

  const [loading, setLoading] = useState(false)
  const [initialLoading, setInitialLoading] = useState(isEditing)
  const [resourceTypes, setResourceTypes] = useState<ResourceType[]>([])
  const [locations, setLocations] = useState<LocationRow[]>([])
  const [selectedLocationByDepth, setSelectedLocationByDepth] = useState<string[]>([])
  const [amenityInput, setAmenityInput] = useState("")

  const [name, setName] = useState("")
  const [description, setDescription] = useState("")
  const [resourceTypeId, setResourceTypeId] = useState("")
  const [capacity, setCapacity] = useState(1)
  const [floor, setFloor] = useState("")
  const [amenities, setAmenities] = useState<string[]>([])
  const [isActive, setIsActive] = useState(true)
  const [imageUrl, setImageUrl] = useState("")

  const locationsById = useMemo(
    () => new Map(locations.map((l) => [l.id, l])),
    [locations],
  )
  const locationChildrenMap = useMemo(
    () => buildLocationChildrenMap(locations),
    [locations],
  )
  const locationLevelOptions = useMemo(() => {
    const levels: Array<{ depth: number; options: LocationRow[] }> = []
    let parentId: string | null = null
    for (let depth = 0; depth < 20; depth += 1) {
      const options = locationChildrenMap.get(parentId) ?? []
      if (options.length === 0) break
      levels.push({ depth, options })
      const selectedAtDepth = selectedLocationByDepth[depth]
      if (!selectedAtDepth) break
      parentId = selectedAtDepth
    }
    return levels
  }, [locationChildrenMap, selectedLocationByDepth])

  // Load resource types
  useEffect(() => {
    const load = async () => {
      const { data } = await supabase
        .from("resource_types")
        .select("*")
        .eq("is_active", true)
        .order("name")
      if (data) setResourceTypes(data)
    }
    void load()
  }, [supabase])

  // Load locations
  useEffect(() => {
    let cancelled = false
    const loadLocations = async () => {
      const res = await fetch("/api/locations")
      const payload = (await res.json().catch(() => null)) as
        | { locations?: LocationRow[]; error?: string }
        | null
      if (!res.ok) {
        if (!cancelled) toast.error(payload?.error ?? "No se pudo cargar ubicaciones")
        return
      }
      if (!cancelled) setLocations(payload?.locations ?? [])
    }
    void loadLocations()
    return () => {
      cancelled = true
    }
  }, [])

  // Hydrate form when editing
  useEffect(() => {
    if (!resource) return
    const metadata = (resource.metadata ?? {}) as {
      locationPathIds?: string[]
      image_url?: string
    }
    setName(resource.name)
    setDescription(resource.description || "")
    setResourceTypeId(resource.resource_type_id)
    setCapacity(resource.capacity ?? 1)
    setFloor(resource.floor || "")
    setAmenities((resource.amenities as string[]) || [])
    setIsActive(resource.is_active ?? true)
    setImageUrl(metadata.image_url || "")
    setSelectedLocationByDepth(
      Array.isArray(metadata.locationPathIds)
        ? metadata.locationPathIds.filter((v) => typeof v === "string")
        : [],
    )
    setInitialLoading(false)
  }, [resource])

  // Set default resource type once loaded (create mode)
  useEffect(() => {
    if (!isEditing && resourceTypes.length > 0 && !resourceTypeId) {
      setResourceTypeId(resourceTypes[0].id)
    }
  }, [resourceTypes, isEditing, resourceTypeId])

  const addAmenity = () => {
    if (amenityInput.trim() && !amenities.includes(amenityInput.trim())) {
      setAmenities((prev) => [...prev, amenityInput.trim()])
      setAmenityInput("")
    }
  }

  const removeAmenity = (amenity: string) => {
    setAmenities((prev) => prev.filter((a) => a !== amenity))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)

    const locationPathIds = getLocationPathIds({
      selectedByDepth: selectedLocationByDepth,
      childrenMap: locationChildrenMap,
    })
    const selectedLocation =
      locationPathIds.length > 0
        ? locationsById.get(locationPathIds[locationPathIds.length - 1])
        : null
    const pathValues = locationPathIds
      .map((id) => locationsById.get(id)?.value)
      .filter(Boolean) as string[]
    const existingMetadata = (resource?.metadata ?? {}) as Record<string, unknown>

    const payload: Record<string, unknown> = {
      name: name.trim(),
      description: description.trim() || null,
      resource_type_id: resourceTypeId,
      capacity,
      floor: floor.trim() || null,
      amenities,
      is_active: isActive,
      metadata: {
        ...existingMetadata,
        locationPathIds,
        locationPathValues: pathValues,
        image_url: imageUrl.trim() || null,
      },
    }

    if (isEditing && resource) {
      const { error } = await (supabase.from("resources") as any)
        .update(payload)
        .eq("id", resource.id)
      if (error) {
        toast.error(
          `Error al actualizar: [${error.code}] ${error.message}${error.details ? ` — ${error.details}` : ""}`,
        )
        setLoading(false)
        return
      }
      toast.success("Recurso actualizado")
    } else {
      const { error } = await (supabase.from("resources") as any).insert(payload)
      if (error) {
        toast.error(
          `Error al crear: [${error.code}] ${error.message}${error.details ? ` — ${error.details}` : ""}`,
        )
        setLoading(false)
        return
      }
      toast.success("Recurso creado")
    }

    setLoading(false)
    router.push("/admin/resources")
  }

  if (isEditing && initialLoading) {
    return (
      <div className="flex items-center justify-center py-16">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-[var(--ds-brand-400)] border-t-transparent" />
      </div>
    )
  }

  return (
    <div className="mx-auto max-w-2xl">
      {/* Header */}
      <div className="flex items-center justify-between border-b border-[var(--ds-neutral-200)] pb-[var(--ds-space-3x)]">
        <h1 className="ds-type-global-l ds-type-semibold text-[var(--ds-text-neutral-default)]">
          {isEditing ? "Editar recurso" : "Nuevo recurso"}
        </h1>
        <Button
          variant="ghost"
          size="icon"
          onClick={() => router.push("/admin/resources")}
          className="h-8 w-8 rounded-[var(--ds-radius-m)] text-[var(--ds-text-neutral-lighter)] hover:bg-[var(--ds-neutral-100)]"
        >
          <X className="h-5 w-5" />
        </Button>
      </div>

      {/* Subtitle */}
      <div className="mt-[var(--ds-space-4x)]">
        <h2 className="ds-type-global-m ds-type-semibold text-[var(--ds-text-neutral-default)]">
          Recurso
        </h2>
        <p className="mt-1 ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
          Creá o editá un recurso reservable: nombre, tipo, ubicación y amenidades.
        </p>
      </div>

      <form onSubmit={handleSubmit} className="mt-[var(--ds-space-4x)] space-y-[var(--ds-space-4x)]">
        {/* Section: Información general */}
        <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-white p-[var(--ds-space-4x)] shadow-[var(--ds-shadow-4dp)]">
          <h3 className="ds-type-global-m ds-type-semibold text-[var(--ds-text-neutral-default)]">
            Información general
          </h3>

          <div className="mt-[var(--ds-space-4x)] space-y-[var(--ds-space-4x)]">
            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Tipo de recurso
              </label>
              <Select value={resourceTypeId} onValueChange={setResourceTypeId}>
                <SelectTrigger className="mt-[var(--ds-space-1x)] 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="Selecciona tipo" />
                </SelectTrigger>
                <SelectContent>
                  {resourceTypes.map((type) => (
                    <SelectItem key={type.id} value={type.id}>
                      {type.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Nombre
              </label>
              <Input
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Ej: Sala Aconcagua"
                required
                className="mt-[var(--ds-space-1x)] 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)]"
                maxLength={255}
              />
              <span className="mt-[var(--ds-space-1x)] block ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                Nombre con el que se mostrará el recurso al reservar.
              </span>
            </div>

            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Descripción (opcional)
              </label>
              <Textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Descripción opcional del recurso"
                rows={3}
                className="mt-[var(--ds-space-1x)] min-h-[80px] rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] bg-white px-[var(--ds-space-2x)] py-[var(--ds-space-2x)] ds-type-global-s text-[var(--ds-text-neutral-default)] placeholder:text-[var(--ds-text-neutral-lighter)]"
              />
            </div>
          </div>
        </div>

        {/* Section: Configuración */}
        <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-white p-[var(--ds-space-4x)] shadow-[var(--ds-shadow-4dp)]">
          <h3 className="ds-type-global-m ds-type-semibold text-[var(--ds-text-neutral-default)]">
            Configuración
          </h3>

          <div className="mt-[var(--ds-space-4x)] space-y-[var(--ds-space-4x)]">
            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Capacidad
              </label>
              <NumericInput
                min={1}
                value={capacity}
                onChange={setCapacity}
                className="mt-[var(--ds-space-1x)] 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)]"
              />
              <span className="mt-[var(--ds-space-1x)] block ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                Cantidad de personas o unidades que admite el recurso.
              </span>
            </div>

            {locationLevelOptions.length > 0 && (
              <div>
                <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                  Ubicación jerárquica
                </label>
                <div className="mt-[var(--ds-space-1x)] space-y-[var(--ds-space-2x)]">
                  {locationLevelOptions.map((level, index) => (
                    <Select
                      key={level.depth}
                      value={selectedLocationByDepth[index] ?? "__none__"}
                      onValueChange={(value) => {
                        setSelectedLocationByDepth((prev) => {
                          const next = prev.slice(0, index)
                          if (value !== "__none__") next[index] = value
                          return next
                        })
                      }}
                    >
                      <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={`Nivel ${index + 1}`} />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="__none__">Sin selección</SelectItem>
                        {level.options.map((location) => (
                          <SelectItem key={location.id} value={location.id}>
                            {location.value}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  ))}
                </div>
                <span className="mt-[var(--ds-space-1x)] block ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                  Jerarquía de ubicación (ej. país, ciudad, oficina).
                </span>
              </div>
            )}

            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Detalle ubicación (piso/box)
              </label>
              <Input
                value={floor}
                onChange={(e) => setFloor(e.target.value)}
                placeholder="Ej: Torre B, Piso 5, Box 12"
                className="mt-[var(--ds-space-1x)] 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)]"
              />
            </div>

            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Amenidades
              </label>
              <div className="mt-[var(--ds-space-1x)] flex gap-[var(--ds-space-2x)]">
                <Input
                  value={amenityInput}
                  onChange={(e) => setAmenityInput(e.target.value)}
                  placeholder="Ej: TV, Pizarra, Proyector"
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault()
                      addAmenity()
                    }
                  }}
                  className="h-10 flex-1 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)]"
                />
                <Button
                  type="button"
                  variant="secondary"
                  onClick={addAmenity}
                  className="rounded-[var(--ds-radius-m)] ds-type-global-xs"
                >
                  Agregar
                </Button>
              </div>
              {amenities.length > 0 && (
                <div className="mt-[var(--ds-space-2x)] flex flex-wrap gap-[var(--ds-space-1x)]">
                  {amenities.map((amenity) => (
                    <span
                      key={amenity}
                      className="inline-flex items-center gap-1 rounded-[var(--ds-radius-m)] bg-[var(--ds-neutral-100)] px-[var(--ds-space-2x)] py-[var(--ds-space-05x)] ds-type-global-xxs text-[var(--ds-text-neutral-default)]"
                    >
                      {amenity}
                      <button
                        type="button"
                        onClick={() => removeAmenity(amenity)}
                        className="ml-1 text-[var(--ds-text-neutral-lighter)] hover:text-[var(--ds-error-700)]"
                        aria-label={`Quitar ${amenity}`}
                      >
                        &times;
                      </button>
                    </span>
                  ))}
                </div>
              )}
              <span className="mt-[var(--ds-space-1x)] block ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                Etiquetas para filtrar (ej. &quot;Tiene proyector&quot;).
              </span>
            </div>
          </div>
        </div>

        {/* Section: Imagen y estado */}
        <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-white p-[var(--ds-space-4x)] shadow-[var(--ds-shadow-4dp)]">
          <h3 className="ds-type-global-m ds-type-semibold text-[var(--ds-text-neutral-default)]">
            Imagen y estado
          </h3>

          <div className="mt-[var(--ds-space-4x)] space-y-[var(--ds-space-4x)]">
            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Imagen del recurso (URL)
              </label>
              <Input
                value={imageUrl}
                onChange={(e) => setImageUrl(e.target.value)}
                placeholder="https://ejemplo.com/imagen.jpg"
                className="mt-[var(--ds-space-1x)] 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)]"
              />
              {imageUrl.trim() ? (
                <div className="relative mt-[var(--ds-space-2x)] inline-block">
                  <img
                    src={imageUrl.trim()}
                    alt="Vista previa"
                    className="h-24 w-40 rounded-[var(--ds-radius-m)] border border-[var(--ds-neutral-200)] object-cover"
                    onError={(e) => {
                      ;(e.target as HTMLImageElement).style.display = "none"
                    }}
                  />
                  <button
                    type="button"
                    onClick={() => setImageUrl("")}
                    className="absolute -right-2 -top-2 flex h-5 w-5 items-center justify-center rounded-full bg-[var(--ds-error-600)] text-white"
                    aria-label="Quitar imagen"
                  >
                    <X className="h-3 w-3" />
                  </button>
                </div>
              ) : (
                <div className="mt-[var(--ds-space-2x)] flex h-24 w-40 items-center justify-center rounded-[var(--ds-radius-m)] border border-dashed border-[var(--ds-neutral-300)] text-[var(--ds-text-neutral-lighter)]">
                  <ImageIcon className="h-6 w-6" />
                </div>
              )}
            </div>

            <div className="flex items-center justify-between rounded-[var(--ds-radius-m)] border border-[var(--ds-neutral-200)] px-[var(--ds-space-3x)] py-[var(--ds-space-3x)]">
              <span className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Activo
              </span>
              <Switch checked={isActive} onCheckedChange={setIsActive} />
            </div>
          </div>
        </div>

        {/* Footer buttons */}
        <div className="flex items-center justify-between border-t border-[var(--ds-neutral-200)] pt-[var(--ds-space-4x)]">
          <Button
            type="button"
            variant="outline"
            onClick={() => router.push("/admin/resources")}
            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 || !name.trim() || !resourceTypeId}
            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)] disabled:opacity-50"
          >
            {loading && <Spinner className="mr-[var(--ds-space-2x)]" />}
            {isEditing ? "Guardar" : "Crear recurso"}
          </Button>
        </div>
      </form>
    </div>
  )
}
