"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 Toasts from "../Toasts";

type props = {
  productIds: string[];
  setProductIds?: Function;
  multiDelete?: boolean;
};

const DeleteProduct: FC<props> = ({
  productIds,
  setProductIds = () => [],
  multiDelete = false,
}) => {
  const queryClient = useQueryClient();
  const [isOpen, setOpen] = useState(false);

  const {
    mutate: deleteProduct,
    isPending,
    isSuccess,
  } = useMutation({
    mutationFn: async () =>
      await axios.delete(`/api/products`, { data: { productId: productIds } }),
    onSuccess: () => {
      setOpen(false);
      setTimeout(() => {
        queryClient.invalidateQueries({ queryKey: ["products"] });
      }, 1000);
      setProductIds([]);
    },
    onError: () => {
      setOpen(false);
    },
  });

  return (
    <>
      {isSuccess && <Toasts message="Product delete successful!" />}
      {multiDelete ? (
        <div
          className="flex items-center gap-x-2"
          onClick={() => setOpen(true)}
        >
          <HiTrash className="text-2xl" />
        </div>
      ) : (
        <Button
          color="failure"
          size="sm"
          className="p-0"
          onClick={() => setOpen(true)}
        >
          <div className="flex items-center gap-x-2">
            <HiTrash className="text-lg" />
            Delete
          </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 product</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">
              <span className="block text-red-500">
                {productIds?.length} record selected
              </span>
              Are you sure you want to delete this product?
            </p>
            <div className="flex items-center gap-x-3">
              <Button color="failure" onClick={() => deleteProduct()}>
                {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;
