"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 { duplicateProduct } from "@/services/duplicate-product";
import { useQueryClient } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";

export default function DuplicateProductDialog({
  id,
  dialogOpen,
  setDialogOpen,
}) {
  const t = useTranslations("vendor");
  const [isPending, setIsPending] = useState(false);
  const queryClient = useQueryClient();

  async function handleDeleteProduct() {
    setIsPending(true);
    const { error, message } = await duplicateProduct(id);
    setIsPending(false);
    setDialogOpen(false);
    if (error) {
      toastError(error.message);
    }
    queryClient.refetchQueries({ queryKey: ["/user/products"] });
    toastSuccess(message);
  }

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