"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { createClient } from "@/lib/supabase/client"
import { Button } from "@/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Plus, MoreVertical, Pencil, Trash2, Upload, Filter, Power, ArrowUp, Loader2 } from "lucide-react"
import { toast } from "sonner"
import { ConfirmDeleteDialog } from "@/components/admin/confirm-delete-dialog"
import { BulkUploadSheet } from "@/components/admin/bulk-upload-sheet"
import type { Database } from "@/lib/supabase/database.types"

type Resource = Database["public"]["Tables"]["resources"]["Row"] & {
  resource_types: { name: string; slug: string } | null
}
type ResourceType = Database["public"]["Tables"]["resource_types"]["Row"]

const PAGE_SIZE = 10

export default function ResourcesAdminPage() {
  const router = useRouter()
  const [resources, setResources] = useState<Resource[]>([])
  const [totalCount, setTotalCount] = useState(0)
  const [resourceTypes, setResourceTypes] = useState<ResourceType[]>([])
  const [loading, setLoading] = useState(true)
  const [loadingMore, setLoadingMore] = useState(false)
  const [filterType, setFilterType] = useState<string>("all")
  const [showFilterMenu, setShowFilterMenu] = useState(false)
  const [deleteTarget, setDeleteTarget] = useState<Resource | null>(null)
  const [showBulkSheet, setShowBulkSheet] = useState(false)
  const supabase = createClient()

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

    const { data: typesData } = await supabase
      .from("resource_types")
      .select("*")
      .eq("is_active", true)
      .order("name")
    if (typesData) setResourceTypes(typesData)

    let query = supabase
      .from("resources")
      .select(`*, resource_types (name, slug)`, { count: "exact" })
      .order("name")
      .range(0, PAGE_SIZE - 1)

    if (filterType !== "all") {
      query = query.eq("resource_type_id", filterType)
    }

    const { data, count } = await query
    if (data) setResources(data as Resource[])
    setTotalCount(count ?? 0)
    setLoading(false)
  }

  const loadMore = async () => {
    setLoadingMore(true)
    const from = resources.length
    const to = from + PAGE_SIZE - 1

    let query = supabase
      .from("resources")
      .select(`*, resource_types (name, slug)`)
      .order("name")
      .range(from, to)

    if (filterType !== "all") {
      query = query.eq("resource_type_id", filterType)
    }

    const { data } = await query
    if (data) setResources((prev) => [...prev, ...(data as Resource[])])
    setLoadingMore(false)
  }

  useEffect(() => {
    fetchData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filterType])

  const handleDelete = async (id: string) => {
    const { error } = await supabase.from("resources").delete().eq("id", id)
    if (error) {
      toast.error(error.message)
      return
    }
    toast.success("Recurso eliminado")
    fetchData()
  }

  const handleToggleActive = async (resource: Resource) => {
    const newValue = !resource.is_active
    const { error } = await supabase
      .from("resources")
      .update({ is_active: newValue })
      .eq("id", resource.id)
    if (error) {
      toast.error(error.message)
      return
    }
    toast.success(newValue ? "Recurso activado" : "Recurso desactivado")
    fetchData()
  }

  const activeFilterLabel = filterType === "all"
    ? null
    : resourceTypes.find((t) => t.id === filterType)?.name

  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)]">
          Recursos
        </h1>
        <div className="flex items-center gap-[var(--ds-space-15x)]">
          {/* Filter button */}
          <DropdownMenu open={showFilterMenu} onOpenChange={setShowFilterMenu}>
            <DropdownMenuTrigger asChild>
              <Button
                variant="outline"
                className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]"
              >
                <Filter className="mr-2 h-4 w-4" />
                {activeFilterLabel ? `Filtrar: ${activeFilterLabel}` : "Filtrar"}
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent
              align="end"
              className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-200)] shadow-[var(--ds-shadow-8dp)]"
            >
              <DropdownMenuItem
                className="ds-type-global-xs text-[var(--ds-text-neutral-default)]"
                onClick={() => setFilterType("all")}
              >
                Todos los tipos
              </DropdownMenuItem>
              {resourceTypes.map((type) => (
                <DropdownMenuItem
                  key={type.id}
                  className="ds-type-global-xs text-[var(--ds-text-neutral-default)]"
                  onClick={() => setFilterType(type.id)}
                >
                  {type.name}
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>

          {/* Create button */}
          <Button
            onClick={() => router.push("/admin/resources/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 recurso
          </Button>

          {/* More actions (bulk) */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                variant="outline"
                size="icon"
                className="h-9 w-9 rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] text-[var(--ds-text-neutral-default)]"
              >
                <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
                className="ds-type-global-xs text-[var(--ds-text-neutral-default)]"
                onClick={() => setShowBulkSheet(true)}
              >
                <Upload className="mr-2 h-4 w-4" />
                Carga masiva de recursos
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Table card */}
      <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-white shadow-[var(--ds-shadow-4dp)]">
        {/* Count */}
        <div className="px-6 py-4">
          <span className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
            {totalCount} {totalCount === 1 ? "recurso" : "recursos"} en total
          </span>
        </div>

        {loading ? (
          <div className="flex items-center justify-center py-12">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-[var(--ds-brand-400)] border-t-transparent" />
          </div>
        ) : (
          <Table>
            <TableHeader>
              <TableRow className="border-[var(--ds-neutral-200)]">
                <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">
                  Nombre
                </TableHead>
                <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">
                  Tipo de recurso
                </TableHead>
                <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">
                  Capacidad
                </TableHead>
                <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">
                  Ubicación
                </TableHead>
                <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">
                  Estado
                </TableHead>
                <TableHead className="w-[48px]" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {resources.map((resource) => {
                const meta = resource.metadata as Record<string, unknown> | null
                const locationPath = meta?.locationPathValues as string[] | undefined
                const locationLabel = locationPath?.join(" > ") ?? "-"

                return (
                  <TableRow
                    key={resource.id}
                    className="border-[var(--ds-neutral-200)] hover:bg-[var(--ds-neutral-100)]"
                  >
                    <TableCell className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                      {resource.name}
                    </TableCell>
                    <TableCell className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
                      {resource.resource_types?.name ?? "-"}
                    </TableCell>
                    <TableCell className="ds-type-global-xs text-[var(--ds-text-neutral-default)]">
                      {resource.capacity ?? "-"}
                    </TableCell>
                    <TableCell className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
                      {locationLabel}
                    </TableCell>
                    <TableCell>
                      <Badge
                        className={
                          resource.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)]"
                        }
                      >
                        {resource.is_active ? "Activo" : "Inactivo"}
                      </Badge>
                    </TableCell>
                    <TableCell className="w-[48px] text-right">
                      <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)] hover:text-[var(--ds-text-neutral-default)]"
                          >
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent
                          align="end"
                          className="min-w-[200px] rounded-[var(--ds-radius-l)] border-[var(--ds-neutral-200)] p-2 shadow-[var(--ds-shadow-8dp)]"
                        >
                          <DropdownMenuItem
                            className="flex items-center gap-3 rounded-[var(--ds-radius-m)] px-3 py-3 ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)] cursor-pointer"
                            onClick={() => router.push(`/admin/resources/${resource.id}/edit`)}
                          >
                            <Pencil className="h-5 w-5" />
                            Editar
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            className="flex items-center gap-3 rounded-[var(--ds-radius-m)] px-3 py-3 ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)] cursor-pointer"
                            onClick={() => handleToggleActive(resource)}
                          >
                            <Power className="h-5 w-5" />
                            {resource.is_active ? "Desactivar" : "Activar"}
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            className="flex items-center gap-3 rounded-[var(--ds-radius-m)] px-3 py-3 ds-type-global-s ds-type-semibold text-red-600 focus:text-red-600 cursor-pointer"
                            onClick={() => setDeleteTarget(resource)}
                          >
                            <Trash2 className="h-5 w-5" />
                            Eliminar
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                )
              })}
              {resources.length === 0 && (
                <TableRow>
                  <TableCell
                    colSpan={7}
                    className="py-12 text-center ds-type-global-xs text-[var(--ds-text-neutral-lighter)]"
                  >
                    No se encontraron recursos
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        )}

        {/* Pagination footer */}
        {!loading && resources.length < totalCount && (
          <div className="flex items-center justify-center border-t border-[var(--ds-neutral-200)] px-6 py-4">
            <div className="flex items-center gap-6">
              <Button
                variant="outline"
                onClick={loadMore}
                disabled={loadingMore}
                className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]"
              >
                {loadingMore ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : null}
                Cargar más
              </Button>
              <span className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
                {resources.length} de {totalCount}
              </span>
              <button
                type="button"
                onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
                className="flex h-8 w-8 items-center justify-center rounded-[var(--ds-radius-m)] border border-[var(--ds-neutral-300)] text-[var(--ds-text-neutral-lighter)] hover:bg-[var(--ds-neutral-100)] hover:text-[var(--ds-text-neutral-default)]"
                aria-label="Ir arriba"
              >
                <ArrowUp className="h-4 w-4" />
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Bulk upload sheet */}
      <BulkUploadSheet
        open={showBulkSheet}
        onOpenChange={setShowBulkSheet}
        onUploadComplete={fetchData}
      />

      {/* Controlled delete dialog */}
      <ConfirmDeleteDialog
        open={!!deleteTarget}
        onOpenChange={(open) => {
          if (!open) setDeleteTarget(null)
        }}
        title={`¿Eliminar "${deleteTarget?.name}"?`}
        description="Se eliminará el recurso de forma permanente."
        onConfirm={async () => {
          if (deleteTarget) await handleDelete(deleteTarget.id)
          setDeleteTarget(null)
        }}
      />
    </div>
  )
}
