"use client"

import { useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Plus, MoreVertical, Eye, Pencil, Trash2, Building2 } from "lucide-react"
import { toast } from "sonner"
import { ConfirmDeleteDialog } from "@/components/admin/confirm-delete-dialog"
import { DynamicIcon } from "@/components/ui/dynamic-icon"
import { createClient } from "@/lib/supabase/client"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

type ResourceType = {
  id: string
  name: string
  slug: string
  icon: string | null
  is_active: boolean
  booking_window_start?: string | null
  booking_window_end?: string | null
  slot_size: string
  time_granularity: string | null
}

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

function formatBookingWindow(row: ResourceType) {
  const a = formatTimeShort(row.booking_window_start)
  const b = formatTimeShort(row.booking_window_end)
  if (a === "—" && b === "—") return "Ventana no definida"
  return `${a}–${b}`
}

export default function ResourceTypesAdminPage() {
  const router = useRouter()
  const [types, setTypes] = useState<ResourceType[]>([])
  const [resourceCounts, setResourceCounts] = useState<Map<string, number>>(new Map())
  const [loading, setLoading] = useState(true)
  const [deleteTarget, setDeleteTarget] = useState<ResourceType | null>(null)

  const supabase = useMemo(() => createClient(), [])

  const fetchData = async () => {
    setLoading(true)
    const { data: typesData } = await supabase
      .from("resource_types")
      .select("*")
      .order("name")

    setTypes((typesData ?? []) as ResourceType[])

    // Get resource counts per type
    const { data: resources } = await supabase
      .from("resources")
      .select("resource_type_id")

    const counts = new Map<string, number>()
    if (resources) {
      for (const r of resources) {
        const current = counts.get(r.resource_type_id) ?? 0
        counts.set(r.resource_type_id, current + 1)
      }
    }
    setResourceCounts(counts)
    setLoading(false)
  }

  useEffect(() => {
    fetchData()
  }, [])

  const handleDelete = async (id: string) => {
    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. Eliminá primero los recursos de este tipo."
          : error.message,
      )
      return
    }
    toast.success("Tipo de recurso eliminado")
    setDeleteTarget(null)
    fetchData()
  }

  return (
    <div className="space-y-[var(--ds-space-4x)]">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="ds-type-global-l ds-type-semibold text-[var(--ds-text-neutral-default)]">
          Tipos de recursos
        </h1>
        <Button
          onClick={() => router.push("/admin/resource-types/new")}
          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)]"
        >
          <Plus className="mr-2 h-4 w-4" />
          Nuevo tipo de recurso
        </Button>
      </div>

      {/* Card Grid */}
      {loading ? (
        <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>
      ) : types.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-[var(--ds-radius-l)] border border-dashed border-[var(--ds-neutral-300)] bg-white py-16">
          <Building2 className="mb-3 h-10 w-10 text-[var(--ds-neutral-400)]" />
          <p className="ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)]">
            No hay tipos de recurso
          </p>
          <p className="mt-1 ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
            Creá el primero para empezar a configurar tus espacios reservables.
          </p>
          <Button
            onClick={() => router.push("/admin/resource-types/new")}
            className="mt-4 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)]"
          >
            <Plus className="mr-2 h-4 w-4" />
            Nuevo tipo de recurso
          </Button>
        </div>
      ) : (
        <div className="grid gap-[var(--ds-space-2x)] sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {types.map((typeRow) => {
            const count = resourceCounts.get(typeRow.id) ?? 0

            return (
              <div
                key={typeRow.id}
                className="relative rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-white px-[var(--ds-space-3x)] py-[var(--ds-space-3x)] shadow-[var(--ds-shadow-4dp)] transition-shadow hover:shadow-[var(--ds-shadow-8dp)]"
              >
                {/* Icon + Menu */}
                <div className="flex items-start justify-between">
                  <div className="flex h-10 w-10 items-center justify-center rounded-[var(--ds-radius-m)] bg-[var(--ds-blueprimary-100)] text-[var(--ds-brand-400)]">
                    <DynamicIcon name={typeRow.icon} className="h-6 w-6" />
                  </div>
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8 rounded-[var(--ds-radius-m)] text-[var(--ds-text-neutral-lighter)] hover:bg-[var(--ds-neutral-100)]"
                      >
                        <MoreVertical className="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent
                      align="end"
                      className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-200)] shadow-[var(--ds-shadow-8dp)]"
                    >
                      <DropdownMenuItem
                        onClick={() => router.push(`/admin/resource-types/${typeRow.id}`)}
                        className="ds-type-global-xs text-[var(--ds-text-neutral-default)]"
                      >
                        <Eye className="mr-2 h-4 w-4" />
                        Ver
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => router.push(`/admin/resource-types/${typeRow.id}/edit`)}
                        className="ds-type-global-xs text-[var(--ds-text-neutral-default)]"
                      >
                        <Pencil className="mr-2 h-4 w-4" />
                        Editar
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => setDeleteTarget(typeRow)}
                        className="ds-type-global-xs text-red-600 focus:text-red-600"
                      >
                        <Trash2 className="mr-2 h-4 w-4" />
                        Eliminar
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>

                {/* Name */}
                <h3 className="mt-[var(--ds-space-2x)] ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)]">
                  {typeRow.name}
                </h3>

                {/* Ventana + Count */}
                <p className="mt-[var(--ds-space-1x)] ds-type-global-xs text-[var(--ds-brand-400)]">
                  {formatBookingWindow(typeRow)} · {count} {count === 1 ? "recurso" : "recursos"}
                </p>
              </div>
            )
          })}
        </div>
      )}

      {/* Delete confirmation modal */}
      {deleteTarget && (
        <ConfirmDeleteDialog
          open={true}
          onOpenChange={() => setDeleteTarget(null)}
          title={`¿Eliminar "${deleteTarget.name}"?`}
          description="Se eliminará el tipo de recurso de forma permanente. Si tiene recursos asociados, no se podrá eliminar."
          onConfirm={() => handleDelete(deleteTarget.id)}
        />
      )}
    </div>
  )
}
