"use client";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { deleteProduct } from "@/services/delete-product";
import { useQueryClient } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";

export default function DeleteProductDialog({ id, dialogOpen, setDialogOpen }) {
  const queryClient = useQueryClient();
  const t = useTranslations("vendor");
  const [isPending, setIsPending] = useState(false);
  async function handleDeleteProduct() {
    setIsPending(true);
    const { error } = await deleteProduct(id);
    setIsPending(false);
    setDialogOpen(false);
    if (error) {
      toastError(error.message);
    }
    toastSuccess(t("delete-success"));
    queryClient.refetchQueries({ queryKey: ["/user/products"] });
  }

  return (
    <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{t("delete-product")}</DialogTitle>
        </DialogHeader>
        <div className="flex gap-8 justify-center">
          <Button
            onClick={handleDeleteProduct}
            className="bg-red-500 hover:bg-red-500/90"
          >
            {isPending ? <Loader2 className="animate-spin" /> : t("delete")}
          </Button>
          <Button variant="outline" onClick={() => setDialogOpen(false)}>
            {t("cancel")}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
