"use client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import axios from "axios";
import { Button, Modal, Spinner } from "flowbite-react";
import { FC, useState } from "react";
import { HiOutlineExclamationCircle, HiTrash } from "react-icons/hi";
import { toast } from "react-toastify";
type props = {
  productId: string;
};

const DeleteProduct: FC<props> = ({ productId }) => {
  const queryClient = useQueryClient();
  const [isOpen, setOpen] = useState(false);

  const {
    mutate: deletestore,
    isPending,
    isSuccess,
  } = useMutation({
    mutationFn: async () => await axios.delete(`/api/products/${productId}`),
    onSuccess: () => {
      setOpen(false);
      queryClient.invalidateQueries({ queryKey: ["products"] });
      toast("product delete success");
    },
    onError: () => {
      setOpen(false);
    },
  });

  return (
    <>
      <Button
        size="xs"
        className="p-0 bg-gray-50 hover:!bg-gray-300"
        onClick={() => setOpen(true)}
      >
        <div className="flex items-center gap-x-2">
          <HiTrash className="text-lg text-red-700" />
        </div>
      </Button>
      <Modal onClose={() => setOpen(false)} show={isOpen} size="md">
        <Modal.Header className="border-b-0 px-6 pb-0 pt-6">
          <span className="sr-only">Delete store</span>
        </Modal.Header>
        <Modal.Body className="px-6 pb-6 pt-0">
          <div className="flex flex-col items-center gap-y-6 text-center">
            <HiOutlineExclamationCircle className="text-7xl text-red-500" />
            <p className="text-xl text-gray-500">
              Are you sure you want to delete this store?
            </p>
            <div className="flex items-center gap-x-3">
              <Button color="failure" onClick={() => deletestore()}>
                {isPending && <Spinner aria-label="Spinner button" size="sm" />}
                Yes, I'm sure
              </Button>
              <Button color="gray" onClick={() => setOpen(false)}>
                No, cancel
              </Button>
            </div>
          </div>
        </Modal.Body>
      </Modal>
    </>
  );
};

export default DeleteProduct;
