"use client"

import { use, useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { createClient } from "@/lib/supabase/client"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { ArrowLeft, Pencil, Trash2 } from "lucide-react"
import { toast } from "sonner"
import { ConfirmDeleteDialog } from "@/components/admin/confirm-delete-dialog"
import { DynamicIcon } from "@/components/ui/dynamic-icon"
import type { Database } from "@/lib/supabase/database.types"

type ResourceType = Database["public"]["Tables"]["resource_types"]["Row"] & {
  reminders_enabled?: boolean | null
}

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

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

function formatSlotSize(slotSize: string | null) {
  const map: Record<string, string> = {
    "15min": "15 minutos",
    "30min": "30 minutos",
    "1h": "1 hora",
  }
  return map[slotSize ?? ""] ?? slotSize
}

export default function ResourceTypeDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params)
  const router = useRouter()
  const supabase = useMemo(() => createClient(), [])

  const [rt, setRt] = useState<ResourceType | null>(null)
  const [resources, setResources] = useState<Resource[]>([])
  const [loading, setLoading] = useState(true)
  const [showDelete, setShowDelete] = useState(false)

  useEffect(() => {
    let cancelled = false
    const load = async () => {
      const [{ data: typeData }, { data: resourcesData }] = await Promise.all([
        supabase.from("resource_types").select("*").eq("id", id).maybeSingle(),
        supabase.from("resources").select("*").eq("resource_type_id", id).order("name"),
      ])

      if (cancelled) return
      if (!typeData) {
        toast.error("Tipo de recurso no encontrado")
        router.push("/admin/resource-types")
        return
      }
      setRt(typeData as ResourceType)
      setResources((resourcesData ?? []) as Resource[])
      setLoading(false)
    }
    void load()
    return () => { cancelled = true }
  }, [id, supabase, router])

  const handleDelete = async () => {
    const { error } = await supabase.from("resource_types").delete().eq("id", id)
    if (error) {
      toast.error(
        error.code === "23503"
          ? "No se puede eliminar: tiene recursos asociados."
          : error.message,
      )
      return
    }
    toast.success("Tipo de recurso eliminado")
    router.push("/admin/resource-types")
  }

  if (loading || !rt) {
    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>
    )
  }

  // Icon from resource type config

  return (
    <div className="mx-auto max-w-2xl space-y-[var(--ds-space-4x)]">
      {/* Back + actions */}
      <div className="flex items-center justify-between">
        <Button
          variant="ghost"
          onClick={() => router.push("/admin/resource-types")}
          className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]"
        >
          <ArrowLeft className="mr-2 h-4 w-4" />
          Volver
        </Button>
        <div className="flex gap-2">
          <Button
            variant="outline"
            onClick={() => router.push(`/admin/resource-types/${id}/edit`)}
            className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs"
          >
            <Pencil className="mr-2 h-4 w-4" />
            Editar
          </Button>
          <Button
            variant="outline"
            onClick={() => setShowDelete(true)}
            className="rounded-[var(--ds-radius-m)] border-red-300 ds-type-global-xs text-red-600 hover:bg-red-50"
          >
            <Trash2 className="mr-2 h-4 w-4" />
            Eliminar
          </Button>
        </div>
      </div>

      {/* Header card */}
      <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-white p-[var(--ds-space-3x)]">
        <div className="flex items-center gap-3">
          <div className="flex h-12 w-12 items-center justify-center rounded-[var(--ds-radius-m)] bg-[var(--ds-blueprimary-100)] text-[var(--ds-brand-400)]">
            <DynamicIcon name={rt.icon} className="h-6 w-6" />
          </div>
          <div>
            <h1 className="ds-type-global-l ds-type-semibold text-[var(--ds-text-neutral-default)]">
              {rt.name}
            </h1>
            <p className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
              {rt.slug}
            </p>
          </div>
          <Badge
            className={
              rt.is_active
                ? "ml-auto rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-success-100)] ds-type-global-xxs ds-type-semibold text-[var(--ds-success-700)]"
                : "ml-auto rounded-[var(--ds-radius-s)] border border-[var(--ds-neutral-300)] bg-white ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]"
            }
          >
            {rt.is_active ? "Activo" : "Inactivo"}
          </Badge>
        </div>

        {rt.description && (
          <p className="mt-3 ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
            {rt.description}
          </p>
        )}

        <div className="mt-4 grid grid-cols-2 gap-4 sm:grid-cols-4">
          <div>
            <span className="ds-type-global-xxs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">Ventana</span>
            <p className="ds-type-global-xs text-[var(--ds-text-neutral-default)]">
              {formatTimeShort(rt.booking_window_start)} – {formatTimeShort(rt.booking_window_end)}
            </p>
          </div>
          <div>
            <span className="ds-type-global-xxs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">Duración mínima</span>
            <p className="ds-type-global-xs text-[var(--ds-text-neutral-default)]">{formatSlotSize(rt.slot_size)}</p>
          </div>
          <div>
            <span className="ds-type-global-xxs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">Granularidad</span>
            <p className="ds-type-global-xs text-[var(--ds-text-neutral-default)]">{rt.time_granularity}</p>
          </div>
        </div>
      </div>

      {/* Resources list */}
      <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-white p-[var(--ds-space-3x)]">
        <h2 className="ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)]">
          Recursos ({resources.length})
        </h2>

        {resources.length === 0 ? (
          <p className="mt-3 ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
            No hay recursos de este tipo.
          </p>
        ) : (
          <div className="mt-3 divide-y divide-[var(--ds-neutral-200)]">
            {resources.map((r) => (
              <div key={r.id} className="flex items-center justify-between py-3">
                <div>
                  <p className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">{r.name}</p>
                  {r.floor && (
                    <p className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">{r.floor}</p>
                  )}
                </div>
                <div className="flex items-center gap-2">
                  <span className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                    Cap: {r.capacity}
                  </span>
                  <Badge
                    className={
                      r.is_active
                        ? "rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-success-100)] ds-type-global-xxs ds-type-semibold text-[var(--ds-success-700)]"
                        : "rounded-[var(--ds-radius-s)] border border-[var(--ds-neutral-300)] bg-white ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]"
                    }
                  >
                    {r.is_active ? "Activo" : "Inactivo"}
                  </Badge>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {showDelete && (
        <ConfirmDeleteDialog
          open={true}
          onOpenChange={() => setShowDelete(false)}
          title={`¿Eliminar "${rt.name}"?`}
          description="Se eliminará el tipo de recurso de forma permanente. Si tiene recursos asociados, no se podrá eliminar."
          onConfirm={handleDelete}
        />
      )}
    </div>
  )
}
