"use client"

import { useEffect, useState, useMemo } from "react"
import { useParams, useRouter } from "next/navigation"
import { createClient } from "@/lib/supabase/client"
import { ResourceForm } from "@/components/admin/resource-form"
import { toast } from "sonner"
import type { Database } from "@/lib/supabase/database.types"

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

export default function EditResourcePage() {
  const params = useParams<{ id: string }>()
  const router = useRouter()
  const supabase = useMemo(() => createClient(), [])
  const [resource, setResource] = useState<Resource | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const load = async () => {
      const { data, error } = await supabase
        .from("resources")
        .select("*")
        .eq("id", params.id)
        .single()

      if (error || !data) {
        toast.error("Recurso no encontrado")
        router.push("/admin/resources")
        return
      }

      setResource(data)
      setLoading(false)
    }
    void load()
  }, [params.id, supabase, router])

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-[var(--ds-brand-400)] border-t-transparent" />
      </div>
    )
  }

  return <ResourceForm resource={resource} />
}
