"use client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import axios from "axios";
import { Button, Modal, Spinner } from "flowbite-react";
import { redirect } from "next/navigation";
import { FC, useState } from "react";
import { HiOutlineExclamationCircle, HiTrash } from "react-icons/hi";
import { toast } from "react-toastify";

type props = {
  url: string;
  name: string;
  keys: string;
  redirectTo?: string;
};

const DeleteRecord: FC<props> = ({ url, name, keys, redirectTo }) => {
  const queryClient = useQueryClient();
  const [isOpen, setOpen] = useState(false);

  const { mutate: deleteRecord, isPending } = useMutation({
    mutationFn: async () => await axios.delete(url),
    onSuccess: () => {
      setOpen(false);
      queryClient.invalidateQueries({ queryKey: [keys] });
      toast.success(`${name} delete successfully!`);
      if (redirectTo) {
        redirect(redirectTo);
      }
    },
    onError: (error: any) => {
      if (error?.response?.data?.error?.error?.message) {
        toast.error(error?.response?.data?.error?.error?.message);
      } else {
        toast.error(`Unable to delete the ${name}!`);
      }
      setOpen(false);
    },
  });

  return (
    <>
      <Button
        size="xs"
        className="p-0 bg-gray-50 hover:!bg-gray-300 dark:bg-gray-800 dark:border"
        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"></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">1 record selected</span>
              Are you sure you want to delete this {name}?
            </p>
            <div className="flex items-center gap-x-3">
              <Button color="failure" onClick={() => deleteRecord()}>
                {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 DeleteRecord;
