"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 { FieldGroup, Field, FieldLabel } from "@/components/ui/field"
import { Spinner } from "@/components/ui/spinner"
import { NumericInput } from "@/components/ui/numeric-input"
import { ImageIcon, X as XIcon } 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 ResourceFormWizardProps {
  resource?: Resource | null
}

const STEPS = [
  {
    number: 1,
    title: "Aspectos generales",
    subItems: ["Detalles"],
  },
  {
    number: 2,
    title: "Configuración",
    subItems: ["Detalles"],
  },
  {
    number: 3,
    title: "Imagen y estado",
    subItems: ["Detalles"],
  },
]

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

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

  const [formData, setFormData] = useState({
    name: "",
    description: "",
    resource_type_id: "",
    capacity: 1,
    floor: "",
    amenities: [] as string[],
    is_active: true,
    image_url: "",
  })

  const locationsById = useMemo(
    () => new Map(locations.map((l) => [l.id, l])),
    [locations],
  )
  const locationChildrenMap = useMemo(
    () => buildLocationChildrenMap(locations),
    [locations],
  )

  // 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) {
      const metadata = (resource.metadata ?? {}) as {
        locationPathIds?: string[]
        image_url?: string
      }
      setFormData({
        name: resource.name,
        description: resource.description || "",
        resource_type_id: resource.resource_type_id,
        capacity: resource.capacity || 1,
        floor: resource.floor || "",
        amenities: (resource.amenities as string[]) || [],
        is_active: resource.is_active ?? true,
        image_url: metadata.image_url || "",
      })
      setSelectedLocationByDepth(
        Array.isArray(metadata.locationPathIds)
          ? metadata.locationPathIds.filter((v) => typeof v === "string")
          : [],
      )
    }
  }, [resource])

  // Set default resource type once loaded
  useEffect(() => {
    if (!isEditing && resourceTypes.length > 0 && !formData.resource_type_id) {
      setFormData((prev) => ({ ...prev, resource_type_id: resourceTypes[0].id }))
    }
  }, [resourceTypes, isEditing, formData.resource_type_id])

  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])

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

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

  const handleSubmit = async () => {
    setLoading(true)

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

    const payload: Record<string, unknown> = {
      name: formData.name,
      description: formData.description || null,
      resource_type_id: formData.resource_type_id,
      capacity: formData.capacity,
      floor: formData.floor || null,
      amenities: formData.amenities,
      is_active: formData.is_active,
      metadata: {
        ...existingMetadata,
        locationPathIds,
        locationPathValues: selectedLocation?.path ?? [],
        image_url: formData.image_url || 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")
  }

  const goNext = () => {
    if (currentStep < STEPS.length - 1) setCurrentStep((s) => s + 1)
    else void handleSubmit()
  }

  const goBack = () => {
    if (currentStep > 0) setCurrentStep((s) => s - 1)
    else router.push("/admin/resources")
  }

  const isNextDisabled = () => {
    if (currentStep === 0) {
      return !formData.resource_type_id || !formData.name.trim()
    }
    return false
  }

  return (
    <div className="flex min-h-[calc(100vh-80px)] flex-col">
      {/* Top bar */}
      <div className="flex items-center justify-between border-b border-[var(--ds-neutral-200)] px-[var(--ds-space-4x)] py-[var(--ds-space-3x)]">
        <h1 className="ds-type-global-l ds-type-semibold text-[var(--ds-text-neutral-default)]">
          {isEditing ? "Editar recurso" : "Crear nuevo recurso"}
        </h1>
        <button
          type="button"
          onClick={() => router.push("/admin/resources")}
          className="flex h-8 w-8 items-center justify-center rounded-[var(--ds-radius-m)] text-[var(--ds-text-neutral-lighter)] hover:bg-[var(--ds-neutral-100)] hover:text-[var(--ds-text-neutral-default)]"
        >
          <XIcon className="h-5 w-5" />
        </button>
      </div>

      {/* Body: sidebar + content */}
      <div className="flex flex-1">
        {/* Sidebar */}
        <aside className="w-[260px] flex-shrink-0 border-r border-[var(--ds-neutral-200)] bg-white py-[var(--ds-space-4x)]">
          <nav className="flex flex-col gap-[var(--ds-space-1x)]">
            {STEPS.map((step, index) => {
              const isActive = index === currentStep
              const isCompleted = index < currentStep
              return (
                <button
                  key={step.number}
                  type="button"
                  onClick={() => {
                    if (index <= currentStep) setCurrentStep(index)
                  }}
                  className={`flex items-start gap-[var(--ds-space-2x)] border-l-[3px] px-[var(--ds-space-3x)] py-[var(--ds-space-2x)] text-left transition-colors ${
                    isActive
                      ? "border-l-[var(--ds-brand-400)] bg-[var(--ds-brand-50,transparent)]"
                      : "border-l-transparent hover:bg-[var(--ds-neutral-100)]"
                  }`}
                >
                  {/* Step number circle */}
                  <span
                    className={`flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full ds-type-global-xxs ds-type-semibold ${
                      isActive
                        ? "bg-[var(--ds-brand-400)] text-white"
                        : isCompleted
                          ? "bg-[var(--ds-success-100)] text-[var(--ds-success-700)]"
                          : "bg-[var(--ds-neutral-200)] text-[var(--ds-text-neutral-lighter)]"
                    }`}
                  >
                    {isCompleted ? "\u2713" : step.number}
                  </span>
                  <div className="flex flex-col">
                    <span
                      className={`ds-type-global-xs ${
                        isActive
                          ? "ds-type-semibold text-[var(--ds-brand-400)]"
                          : "text-[var(--ds-text-neutral-default)]"
                      }`}
                    >
                      {step.title}
                    </span>
                    {step.subItems.map((sub) => (
                      <span
                        key={sub}
                        className="mt-[var(--ds-space-half)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]"
                      >
                        {sub}
                      </span>
                    ))}
                  </div>
                </button>
              )
            })}
          </nav>
        </aside>

        {/* Content area */}
        <main className="flex flex-1 flex-col bg-[var(--ds-neutral-100,#f5f5f5)]">
          <div className="flex-1 overflow-y-auto px-[var(--ds-space-6x)] py-[var(--ds-space-4x)]">
            <div className="mx-auto max-w-[640px] rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-white p-[var(--ds-space-4x)] shadow-[var(--ds-shadow-4dp)]">
              {/* Step 1: Aspectos generales */}
              {currentStep === 0 && (
                <FieldGroup className="gap-[var(--ds-space-3x)]">
                  <h2 className="ds-type-global-m ds-type-semibold text-[var(--ds-text-neutral-default)]">
                    Aspectos generales
                  </h2>

                  <Field>
                    <FieldLabel className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                      Tipo de recurso
                    </FieldLabel>
                    <Select
                      value={formData.resource_type_id}
                      onValueChange={(value) =>
                        setFormData((prev) => ({ ...prev, resource_type_id: value }))
                      }
                    >
                      <SelectTrigger className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs">
                        <SelectValue placeholder="Selecciona tipo" />
                      </SelectTrigger>
                      <SelectContent>
                        {resourceTypes.map((type) => (
                          <SelectItem key={type.id} value={type.id}>
                            {type.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </Field>

                  <Field>
                    <FieldLabel className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                      Nombre
                    </FieldLabel>
                    <Input
                      value={formData.name}
                      onChange={(e) =>
                        setFormData((prev) => ({ ...prev, name: e.target.value }))
                      }
                      placeholder="Ej: Sala Aconcagua"
                      required
                      className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs"
                    />
                  </Field>

                  <Field>
                    <FieldLabel className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                      Descripcion
                    </FieldLabel>
                    <Textarea
                      value={formData.description}
                      onChange={(e) =>
                        setFormData((prev) => ({ ...prev, description: e.target.value }))
                      }
                      placeholder="Descripcion opcional del recurso"
                      rows={3}
                      className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs"
                    />
                  </Field>
                </FieldGroup>
              )}

              {/* Step 2: Configuracion */}
              {currentStep === 1 && (
                <FieldGroup className="gap-[var(--ds-space-3x)]">
                  <h2 className="ds-type-global-m ds-type-semibold text-[var(--ds-text-neutral-default)]">
                    Configuracion
                  </h2>

                  <Field>
                    <FieldLabel className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                      Capacidad
                    </FieldLabel>
                    <NumericInput
                      min={1}
                      value={formData.capacity}
                      onChange={(v) =>
                        setFormData((prev) => ({ ...prev, capacity: v }))
                      }
                      className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs"
                    />
                  </Field>

                  {locationLevelOptions.length > 0 && (
                    <Field>
                      <FieldLabel className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                        Ubicacion jerarquica
                      </FieldLabel>
                      <div className="space-y-2">
                        {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="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs">
                              <SelectValue placeholder={`Nivel ${index + 1}`} />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="__none__">
                                Sin seleccion en este nivel
                              </SelectItem>
                              {level.options.map((location) => (
                                <SelectItem key={location.id} value={location.id}>
                                  {location.value}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        ))}
                      </div>
                    </Field>
                  )}

                  <Field>
                    <FieldLabel className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                      Detalle ubicacion (piso/box)
                    </FieldLabel>
                    <Input
                      value={formData.floor}
                      onChange={(e) =>
                        setFormData((prev) => ({ ...prev, floor: e.target.value }))
                      }
                      placeholder="Ej: Torre B, Piso 5, Box 12"
                      className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs"
                    />
                  </Field>

                  <Field>
                    <FieldLabel className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                      Amenidades
                    </FieldLabel>
                    <div className="flex gap-2">
                      <Input
                        value={amenityInput}
                        onChange={(e) => setAmenityInput(e.target.value)}
                        placeholder="Ej: TV, Pizarra, etc."
                        onKeyDown={(e) => {
                          if (e.key === "Enter") {
                            e.preventDefault()
                            addAmenity()
                          }
                        }}
                        className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs"
                      />
                      <Button
                        type="button"
                        variant="secondary"
                        onClick={addAmenity}
                        className="rounded-[var(--ds-radius-m)] ds-type-global-xs"
                      >
                        Agregar
                      </Button>
                    </div>
                    {formData.amenities.length > 0 && (
                      <div className="mt-2 flex flex-wrap gap-2">
                        {formData.amenities.map((amenity) => (
                          <span
                            key={amenity}
                            className="inline-flex items-center gap-1 rounded-[var(--ds-radius-m)] bg-[var(--ds-neutral-100)] px-2 py-1 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-red-600"
                            >
                              &times;
                            </button>
                          </span>
                        ))}
                      </div>
                    )}
                  </Field>
                </FieldGroup>
              )}

              {/* Step 3: Imagen y estado */}
              {currentStep === 2 && (
                <FieldGroup className="gap-[var(--ds-space-3x)]">
                  <h2 className="ds-type-global-m ds-type-semibold text-[var(--ds-text-neutral-default)]">
                    Imagen y estado
                  </h2>

                  <Field>
                    <FieldLabel className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                      Imagen del recurso (URL)
                    </FieldLabel>
                    <Input
                      value={formData.image_url}
                      onChange={(e) =>
                        setFormData((prev) => ({ ...prev, image_url: e.target.value }))
                      }
                      placeholder="https://ejemplo.com/imagen.jpg"
                      className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs"
                    />
                    {formData.image_url && (
                      <div className="relative mt-2 inline-block">
                        <img
                          src={formData.image_url}
                          alt="Preview"
                          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={() =>
                            setFormData((prev) => ({ ...prev, image_url: "" }))
                          }
                          className="absolute -right-2 -top-2 flex h-5 w-5 items-center justify-center rounded-full bg-[var(--ds-error-600)] text-white"
                        >
                          <XIcon className="h-3 w-3" />
                        </button>
                      </div>
                    )}
                    {!formData.image_url && (
                      <div className="mt-2 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>
                    )}
                  </Field>

                  <Field orientation="horizontal">
                    <div className="flex items-center justify-between rounded-[var(--ds-radius-m)] border border-[var(--ds-neutral-200)] px-[var(--ds-space-2x)] py-[var(--ds-space-2x)]">
                      <span className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                        Activo
                      </span>
                      <Switch
                        checked={formData.is_active}
                        onCheckedChange={(checked) =>
                          setFormData((prev) => ({ ...prev, is_active: checked }))
                        }
                      />
                    </div>
                  </Field>
                </FieldGroup>
              )}
            </div>
          </div>

          {/* Bottom navigation */}
          <div className="flex items-center justify-between border-t border-[var(--ds-neutral-200)] bg-white px-[var(--ds-space-6x)] py-[var(--ds-space-3x)]">
            <Button
              type="button"
              variant="outline"
              onClick={goBack}
              className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs text-[var(--ds-text-neutral-default)]"
            >
              Volver
            </Button>
            <Button
              type="button"
              onClick={goNext}
              disabled={loading || isNextDisabled()}
              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-2" />}
              {currentStep === STEPS.length - 1 ? "Guardar" : "Siguiente"}
            </Button>
          </div>
        </main>
      </div>
    </div>
  )
}
