"use client"

import { useEffect, useMemo, useState } 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 { NumericInput } from "@/components/ui/numeric-input"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Switch } from "@/components/ui/switch"
import { Spinner } from "@/components/ui/spinner"
import { toast } from "sonner"
import { X } from "lucide-react"
import { LucideIconSelect } from "@/components/ui/lucide-icon-select"
import {
  minutesFromValueUnit,
  type RuleUnit,
  valueUnitFromMinutes,
} from "@/lib/reservations/rules"
import { parseTimeToMinutesSinceMidnight } from "@/lib/booking"

type SlotSize = "15min" | "30min" | "1h"
type TimeGranularity = "5min" | "10min" | "15min" | "30min" | "60min"

const SLOT_SIZE_OPTIONS: { value: SlotSize; label: string }[] = [
  { value: "15min", label: "15 minutos" },
  { value: "30min", label: "30 minutos" },
  { value: "1h", label: "1 hora" },
]

function timeInputValueFromDb(t: string | null | undefined): string {
  if (!t) return "08:00"
  return t.length >= 5 ? t.slice(0, 5) : t
}

function timeForDbFromInput(v: string): string {
  if (!v) return "08:00:00"
  return v.length === 5 ? `${v}:00` : v
}

const GRANULARITY_OPTIONS: { value: TimeGranularity; label: string }[] = [
  { value: "5min", label: "5 minutos" },
  { value: "10min", label: "10 minutos" },
  { value: "15min", label: "15 minutos" },
  { value: "30min", label: "30 minutos" },
  { value: "60min", label: "1 hora" },
]

function slugify(s: string) {
  return s
    .toLowerCase()
    .trim()
    .replace(/\s+/g, "-")
    .replace(/[^a-z0-9-]/g, "")
}

interface ResourceTypeFormProps {
  resourceTypeId?: string
}

export function ResourceTypeForm({ resourceTypeId }: ResourceTypeFormProps) {
  const router = useRouter()
  const supabase = useMemo(() => createClient(), [])
  const isEditing = !!resourceTypeId

  const [loading, setLoading] = useState(false)
  const [initialLoading, setInitialLoading] = useState(isEditing)
  const [name, setName] = useState("")
  const [slug, setSlug] = useState("")
  const [icon, setIcon] = useState("")
  const [description, setDescription] = useState("")
  const [isActive, setIsActive] = useState(true)

  const [bookingWindowStart, setBookingWindowStart] = useState("08:00")
  const [bookingWindowEnd, setBookingWindowEnd] = useState("20:00")
  const [slotSize, setSlotSize] = useState<SlotSize>("30min")
  const [timeGranularity, setTimeGranularity] = useState<TimeGranularity>("15min")

  const [remindersEnabled, setRemindersEnabled] = useState(false)
  const [reminderAdvanceValue, setReminderAdvanceValue] = useState(24)
  const [reminderAdvanceUnit, setReminderAdvanceUnit] = useState<RuleUnit>("hours")
  const [bookingAdvanceValue, setBookingAdvanceValue] = useState(10)
  const [bookingAdvanceUnit, setBookingAdvanceUnit] = useState<RuleUnit>("days")
  const [cancellationValue, setCancellationValue] = useState(5)
  const [cancellationUnit, setCancellationUnit] = useState<RuleUnit>("hours")
  const [editingValue, setEditingValue] = useState(5)
  const [editingUnit, setEditingUnit] = useState<RuleUnit>("hours")

  // Load existing data for edit mode
  useEffect(() => {
    if (!resourceTypeId) return
    let cancelled = false

    const load = async () => {
      const { data: rt } = await supabase
        .from("resource_types")
        .select("*")
        .eq("id", resourceTypeId)
        .maybeSingle()

      if (cancelled || !rt) {
        if (!cancelled) {
          toast.error("No se encontró el tipo de recurso")
          router.push("/admin/resource-types")
        }
        return
      }

      setName(rt.name)
      setSlug(rt.slug)
      setIcon(rt.icon || "")
      setDescription(rt.description || "")
      setIsActive(rt.is_active ?? true)
      setBookingWindowStart(timeInputValueFromDb(rt.booking_window_start))
      setBookingWindowEnd(timeInputValueFromDb(rt.booking_window_end))
      const rawSlot = rt.slot_size ?? "30min"
      setSlotSize(
        rawSlot === "15min" || rawSlot === "30min" || rawSlot === "1h" ? rawSlot : "30min",
      )
      setTimeGranularity((rt.time_granularity as TimeGranularity) ?? "15min")
      setRemindersEnabled((rt as any).reminders_enabled ?? false)

      const reminderMinutes = (rt as any).reminder_advance_minutes
      const reminderAdvance = valueUnitFromMinutes(
        typeof reminderMinutes === "number" ? reminderMinutes : null,
        { value: 24, unit: "hours" },
      )
      setReminderAdvanceValue(reminderAdvance.value)
      setReminderAdvanceUnit(reminderAdvance.unit)

      const { data: policy } = await supabase
        .from("resource_policies")
        .select("*")
        .eq("resource_type_id", resourceTypeId)
        .limit(1)
        .maybeSingle()

      if (cancelled) return

      const p = (policy ?? {}) as {
        booking_advance_minutes?: number | null
        cancellation_deadline_minutes?: number | null
        editing_deadline_minutes?: number | null
      }

      const booking = valueUnitFromMinutes(p.booking_advance_minutes, { value: 10, unit: "days" })
      setBookingAdvanceValue(booking.value)
      setBookingAdvanceUnit(booking.unit)

      const cancellation = valueUnitFromMinutes(p.cancellation_deadline_minutes, { value: 5, unit: "hours" })
      setCancellationValue(cancellation.value)
      setCancellationUnit(cancellation.unit)

      const editing = valueUnitFromMinutes(p.editing_deadline_minutes, { value: cancellation.value, unit: cancellation.unit })
      setEditingValue(editing.value)
      setEditingUnit(editing.unit)

      setInitialLoading(false)
    }

    void load()
    return () => { cancelled = true }
  }, [resourceTypeId, supabase, router])

  // Auto-generate slug from name (no campo visible para el usuario)
  useEffect(() => {
    if (!isEditing && name) setSlug(slugify(name))
  }, [name, isEditing])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const finalSlug = slugify(slug) || slugify(name)
    if (!finalSlug || !name.trim()) return

    const ws = timeForDbFromInput(bookingWindowStart)
    const we = timeForDbFromInput(bookingWindowEnd)
    if (parseTimeToMinutesSinceMidnight(we) <= parseTimeToMinutesSinceMidnight(ws)) {
      toast.error("El horario de fin debe ser mayor al de inicio")
      return
    }

    setLoading(true)

    const reminderAdvanceMinutes = minutesFromValueUnit(reminderAdvanceValue, reminderAdvanceUnit)

    const row = {
      slug: finalSlug,
      name: name.trim(),
      icon: icon.trim() || null,
      description: description.trim() || null,
      is_active: isActive,
      booking_unit: "hour" as const,
      booking_window_start: ws,
      booking_window_end: we,
      slot_size: slotSize,
      time_granularity: timeGranularity,
      reminders_enabled: remindersEnabled,
      reminder_advance_minutes: reminderAdvanceMinutes,
    }

    const bookingAdvanceMinutes = minutesFromValueUnit(bookingAdvanceValue, bookingAdvanceUnit)
    const cancellationDeadlineMinutes = minutesFromValueUnit(cancellationValue, cancellationUnit)
    const editingDeadlineMinutes = minutesFromValueUnit(editingValue, editingUnit)

    let targetTypeId = resourceTypeId ?? null

    if (isEditing) {
      const { error } = await (supabase.from("resource_types") as any).update(row).eq("id", resourceTypeId)
      if (error) {
        toast.error(error.message)
        setLoading(false)
        return
      }
      targetTypeId = resourceTypeId!
    } else {
      const { data: createdType, error } = await (supabase.from("resource_types") as any)
        .insert(row)
        .select("id")
        .maybeSingle()
      if (error) {
        if (error.code === "42501") {
          toast.error("Sin permiso. Ejecuta scripts/003_rls_resources_write_authenticated.sql en Supabase.")
        } else {
          toast.error(error.message)
        }
        setLoading(false)
        return
      }
      targetTypeId = createdType?.id ?? null
    }

    if (!targetTypeId) {
      toast.error("No se pudo resolver el tipo de recurso")
      setLoading(false)
      return
    }

    // Upsert policy
    const policyPayload = {
      resource_type_id: targetTypeId,
      booking_advance_minutes: bookingAdvanceMinutes,
      cancellation_deadline_minutes: cancellationDeadlineMinutes,
      editing_deadline_minutes: editingDeadlineMinutes,
      max_advance_days: Math.max(1, Math.ceil(bookingAdvanceMinutes / (24 * 60))),
    }

    const { data: existingPolicy } = await supabase
      .from("resource_policies")
      .select("id")
      .eq("resource_type_id", targetTypeId)
      .limit(1)
      .maybeSingle()

    if (existingPolicy?.id) {
      const { error: policyError } = await (supabase.from("resource_policies") as any)
        .update(policyPayload)
        .eq("id", existingPolicy.id)
      if (policyError) {
        toast.error(policyError.message)
        setLoading(false)
        return
      }
    } else {
      const { error: policyError } = await (supabase.from("resource_policies") as any).insert(policyPayload)
      if (policyError) {
        toast.error(policyError.message)
        setLoading(false)
        return
      }
    }

    toast.success(isEditing ? "Tipo de recurso actualizado" : "Tipo de recurso creado")
    router.push("/admin/resource-types")
  }

  if (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 tipo de recurso" : "Nuevo tipo de recurso"}
        </h1>
        <Button
          variant="ghost"
          size="icon"
          onClick={() => router.push("/admin/resource-types")}
          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)]">
          Tipo de recurso
        </h2>
        <p className="mt-1 ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
          Clasificamos los recursos por tipo. Por ejemplo: &quot;salas de reunión&quot;,
          &quot;escritorios&quot;, etc.
          Podés crear tu tipo de recurso aquí.
        </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)]">
            {/* Nombre */}
            <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 de reunión, Escritorio"
                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}
              />
              <div className="mt-[var(--ds-space-1x)] flex justify-between">
                <span className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                  Nombre con el que los empleados verán este tipo al reservar.
                </span>
                <span className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                  {name.length}/255
                </span>
              </div>
            </div>

            {/* Ícono con vista previa */}
            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Ícono (opcional)
              </label>
              <LucideIconSelect
                value={icon}
                onValueChange={setIcon}
                placeholder="Ej: users, car, monitor, phone"
                className="mt-[var(--ds-space-1x)]"
              />
            </div>

            {/* Descripción */}
            <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)}
                rows={2}
                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 del tipo de recurso */}
        <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 del tipo de recurso
          </h3>

          <div className="mt-[var(--ds-space-4x)] space-y-[var(--ds-space-4x)]">
            <div className="grid grid-cols-1 gap-[var(--ds-space-3x)] sm:grid-cols-2">
              <div>
                <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                  Inicio de ventana de reserva
                </label>
                <Input
                  type="time"
                  value={bookingWindowStart}
                  onChange={(e) => setBookingWindowStart(e.target.value)}
                  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)]"
                />
              </div>
              <div>
                <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                  Fin de ventana de reserva
                </label>
                <Input
                  type="time"
                  value={bookingWindowEnd}
                  onChange={(e) => setBookingWindowEnd(e.target.value)}
                  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)]"
                />
              </div>
            </div>
            <span className="-mt-2 block ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
              Horario local permitido para iniciar y terminar reservas. Siempre por franjas horarias; el usuario puede elegir día completo dentro de esta ventana.
            </span>

            {/* Duración mínima (slot size) */}
            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Duración mínima de reserva
              </label>
              <Select value={slotSize} onValueChange={(v) => setSlotSize(v as SlotSize)}>
                <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 />
                </SelectTrigger>
                <SelectContent>
                  {SLOT_SIZE_OPTIONS.map((opt) => (
                    <SelectItem key={opt.value} value={opt.value}>
                      {opt.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <span className="mt-[var(--ds-space-1x)] block ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                Tiempo mínimo de una reserva. El usuario puede extender por encima de este mínimo.
              </span>
            </div>

            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Granularidad de la grilla
              </label>
              <Select value={timeGranularity} onValueChange={(v) => setTimeGranularity(v as TimeGranularity)}>
                <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 />
                </SelectTrigger>
                <SelectContent>
                  {GRANULARITY_OPTIONS.map((opt) => (
                    <SelectItem key={opt.value} value={opt.value}>
                      {opt.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <span className="mt-[var(--ds-space-1x)] block ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                Paso entre horarios mostrados al reservar (inicio y duraciones).
              </span>
            </div>
          </div>
        </div>

        {/* Section: Reglas y políticas */}
        <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)]">
            Reglas y políticas
          </h3>

          <div className="mt-[var(--ds-space-4x)] space-y-[var(--ds-space-4x)]">
            {/* Recordatorio */}
            <div className="space-y-[var(--ds-space-3x)]">
              <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)]">
                <div>
                  <span className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                    Enviar recordatorio por email
                  </span>
                  <p className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                    Envía un email al usuario antes de su reserva.
                  </p>
                </div>
                <Switch checked={remindersEnabled} onCheckedChange={setRemindersEnabled} />
              </div>

              {remindersEnabled && (
                <div className="rounded-[var(--ds-radius-m)] border border-[var(--ds-neutral-200)] bg-[var(--ds-neutral-100)] px-[var(--ds-space-3x)] py-[var(--ds-space-3x)]">
                  <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                    Antelación del recordatorio
                  </label>
                  <p className="mt-[var(--ds-space-05x)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                    Con cuánta anticipación se envía el email antes del inicio de la reserva.
                  </p>
                  <div className="mt-[var(--ds-space-2x)] grid grid-cols-2 gap-[var(--ds-space-3x)] sm:max-w-[280px]">
                    <NumericInput
                      min={1}
                      value={reminderAdvanceValue}
                      onChange={setReminderAdvanceValue}
                      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)]"
                    />
                    <Select value={reminderAdvanceUnit} onValueChange={(v) => setReminderAdvanceUnit(v as RuleUnit)}>
                      <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 />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="hours">Horas</SelectItem>
                        <SelectItem value="days">Días</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              )}
            </div>

            {/* Antelación máxima */}
            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Antelación máxima para reservar
              </label>
              <div className="mt-[var(--ds-space-1x)] grid grid-cols-2 gap-[var(--ds-space-3x)]">
                <NumericInput
                  min={1}
                  value={bookingAdvanceValue}
                  onChange={setBookingAdvanceValue}
                  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)]"
                />
                <Select value={bookingAdvanceUnit} onValueChange={(v) => setBookingAdvanceUnit(v as RuleUnit)}>
                  <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 />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="hours">Horas</SelectItem>
                    <SelectItem value="days">Días</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Límite cancelación */}
            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Límite para cancelar
              </label>
              <div className="mt-[var(--ds-space-1x)] grid grid-cols-2 gap-[var(--ds-space-3x)]">
                <NumericInput
                  min={1}
                  value={cancellationValue}
                  onChange={setCancellationValue}
                  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)]"
                />
                <Select value={cancellationUnit} onValueChange={(v) => setCancellationUnit(v as RuleUnit)}>
                  <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 />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="hours">Horas</SelectItem>
                    <SelectItem value="days">Días</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Límite edición */}
            <div>
              <label className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                Límite para editar
              </label>
              <div className="mt-[var(--ds-space-1x)] grid grid-cols-2 gap-[var(--ds-space-3x)]">
                <NumericInput
                  min={1}
                  value={editingValue}
                  onChange={setEditingValue}
                  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)]"
                />
                <Select value={editingUnit} onValueChange={(v) => setEditingUnit(v as RuleUnit)}>
                  <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 />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="hours">Horas</SelectItem>
                    <SelectItem value="days">Días</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Activo */}
            <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/resource-types")}
            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()}
            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)]" />}
            Guardar
          </Button>
        </div>
      </form>
    </div>
  )
}
