"use client";
import { deleteRecord } from "@/utils/fetch";
import { useParseError } from "@/utils/lib/helpers";
import { useQueryClient } from "@tanstack/react-query";
import { Button, Checkbox, Label, Modal, Spinner } from "flowbite-react";
import { useRouter } 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;
  customButton?: boolean;
  buttonTitle?: string;
  color?: string;
  type?: string;
  message?: string;
  conditional?: boolean;
  conditionalMessage?: string;
  conditionalParams?: string;
};

const DeleteItem: FC<props> = ({
  url: initUrl,
  name,
  keys,
  customButton = false,
  buttonTitle = "",
  color = "white",
  redirectTo = undefined,
  type = "row",
  message = null,
  conditional = false,
  conditionalMessage = undefined,
  conditionalParams = "",
}) => {
  const queryClient = useQueryClient();
  const [isOpen, setOpen] = useState(false);
  const [isLoading, setLoading] = useState(false);
  const router = useRouter();
  const [url, setUrl] = useState(initUrl);
  const deleteItems = async () => {
    setLoading(true);
    const response = await deleteRecord(url);
    if (response?.success) {
      setLoading(false);
      toast.success(`${name} delete successfully!`);
      queryClient.invalidateQueries({ queryKey: [keys] });
      setOpen(false);
      if (redirectTo) {
        router.push(redirectTo);
      }
    } else {
      toast.error(useParseError(response));

      setLoading(false);
      setOpen(false);
    }
  };
  const setDeleteCondition = (event: any) => {
    if (event?.target?.checked) {
      setUrl(`${url}?${conditionalParams}`);
    } else {
      setUrl(url);
    }
  };
  return (
    <>
      {type === "dropdown" ? (
        <div
          className="w-full flex"
          color={"white"}
          onClick={() => setOpen(true)}
        >
          <div>
            <HiTrash className="text-lg text-gray-700" />
          </div>
          <div className="ml-2">Delete</div>
        </div>
      ) : (
        <Button
          size="xs"
          className={`p-0 bg-gray-50  hover:!bg-gray-300 dark:bg-gray-800 dark:border ${customButton ? "bg-red-600 text-white hover:!bg-red-500" : ""}`}
          onClick={() => setOpen(true)}
          color={color}
        >
          {customButton ? (
            <div className="flex">
              <HiTrash className="text-lg text-white mr-1 mt-1 " />
              {buttonTitle && (
                <span className="block mt-1.5">{buttonTitle}</span>
              )}
            </div>
          ) : (
            <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" />
            <div className="text-xl text-gray-500">
              <span className="block text-red-500">
                {message ? message : ""}
              </span>
              {!conditionalMessage && (
                <div>Are you sure you want to delete this {name}?</div>
              )}
              {conditional && conditionalMessage && (
                <>
                  <div>Are you sure you want to delete this {name}?</div>
                  <Checkbox
                    id={name}
                    onChange={(event: any) => setDeleteCondition(event)}
                  />
                  <Label
                    htmlFor={name}
                    className="ml-2 capitalize dark:text-gray-400 cursor-pointer"
                  >
                    {conditionalMessage}
                  </Label>
                </>
              )}
            </div>
            <div className="flex items-center gap-x-3">
              <Button color="failure" onClick={() => deleteItems()}>
                {isLoading && <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 DeleteItem;
