"use client"

import { Trash } from "lucide-react"
import { useRouter } from "next/navigation"
import { useTransition } from "react"
import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import { deleteCategoryAction } from "@/lib/actions/category.actions"

export default function DeleteCategoryButton({
  categoryId,
}: {
  categoryId: string
}) {
  const router = useRouter()
  const [isPending, startTransition] = useTransition()

  const handleDelete = (formData: FormData) => {
    startTransition(async () => {
      const response = await deleteCategoryAction(formData)

      if (!response.success && response.errors?.id) {
        toast.error(response.errors.id[0])
        return
      }

      if (response.success) {
        toast.success(response.message)
        router.refresh()
      } else {
        toast.error(response.message ?? "Unknown error")
      }
    })
  }

  return (
    <form action={handleDelete}>
      <input type="hidden" name="id" value={categoryId} />
      <Button
        type="submit"
        className="btn btn-error"
        size="icon"
        variant="outline"
        disabled={isPending}
      >
        <Trash />
      </Button>
    </form>
  )
}
