"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 = {
  roleIds: string[];
  setRoleIds?: Function;
  multiDelete?: boolean;
};

const DeleteRole: FC<props> = ({
  roleIds,
  setRoleIds = () => [],
  multiDelete = false,
}) => {
  const queryClient = useQueryClient();
  const [isOpen, setOpen] = useState(false);

  const {
    mutate: deleteRole,
    isPending,
    isSuccess,
  } = useMutation({
    mutationFn: async () =>
      await axios.delete(`/api/roles`, { data: { roleId: roleIds } }),
    onSuccess: () => {
      setOpen(false);
      setTimeout(() => {
        queryClient.invalidateQueries({ queryKey: ["roles"] });
      }, 1000);
      setRoleIds([]);
    },
    onError: () => {
      setOpen(false);
    },
  });

  return (
    <>
      {isSuccess && <Toasts message="Role delete successful!" />}
      <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 role</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">
                {roleIds?.length} record selected
              </span>
              Are you sure you want to delete this role?
            </p>
            <div className="flex items-center gap-x-3">
              <Button color="failure" onClick={() => deleteRole()}>
                {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 DeleteRole;
