import { postData } from "@/utils/fetch";
import { useParseError } from "@/utils/lib/helpers";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Checkbox, Label, Modal } from "flowbite-react";
import { FC, useEffect, useState } from "react";
import { HiOutlineRefresh } from "react-icons/hi";
import { toast } from "react-toastify";
import ActionButton from "../action-button";
import Button from "../Button";
import Spinner from "../spinner";

const SmsResendAll: FC = () => {
  const queryClient = useQueryClient();
  const [isOpen, setOpen] = useState(false);
  const [allSms, setAllSms] = useState(true);
  const [smsType, setSmsType] = useState<string[]>(["all"]);
  const { mutate: resendAll, isPending } = useMutation({
    mutationFn: async (smsData: any) => {
      const data = await postData(`/api/v1/communication-queue/resend-all`, smsData as any);
      console.log(data);
      if (!data?.success) {
        throw data;
      }
      return data?.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ["communication-queue"] });
      toast.success(`Resend sms successful!`);
    },
    onError: (error: any) => {
      toast.error(useParseError(error));
    },
  });

  const sms_type = ["custom", "invoice_due", "invoice_due_reminder"];
  const handleSmsType = (event: any) => {
    const sms_type = event.target.value;
    if (event.target.checked) {
      setSmsType((prev: string[]) => [...prev, sms_type]);
    } else {
      setSmsType((prev) => prev.filter((item: string) => item !== sms_type));
    }
  };

  const handelAllSms = (event: any) => {
    if (event.target.checked) {
      setSmsType([]);
      setAllSms(true);
    }
  };

  useEffect(() => {
    if (smsType?.length > 1) {
      if (smsType.includes("all")) {
        setSmsType((prev) => prev.filter((item: string) => item !== "all"));
      }
      setAllSms(false);
    }
    if (smsType?.length === 0 && !smsType?.includes("all")) {
      setSmsType((prev: string[]) => [...prev, "all"]);
      setAllSms(true);
    }
  }, [smsType]);

  return (
    <div>
      <Modal onClose={() => setOpen(false)} show={isOpen} size={"md"}>
        <Modal.Header className="border-b border-gray-200 !p-6 dark:border-gray-700">
          <p className="font-normal">Resend All SMS</p>
        </Modal.Header>
        <Modal.Body>
          <div className="block">
            <Checkbox
              id={`type-all`}
              name="sms_type"
              value={"all"}
              checked={allSms}
              onChange={(event) => handelAllSms(event)}
            />
            <Label
              htmlFor={`type-all`}
              className="mx-2 capitalize dark:text-gray-400 cursor-pointer"
            >
              {"all"}
            </Label>
            {sms_type.map((types) => (
              <div key={types} className="block my-2">
                <Checkbox
                  id={`type-${types}`}
                  name="sms_type"
                  checked={smsType?.includes(types)}
                  value={types}
                  onChange={(event) => handleSmsType(event)}
                />
                <Label
                  htmlFor={`type-${types}`}
                  className="mx-2 capitalize dark:text-gray-400 cursor-pointer"
                >
                  {types?.split("_").join(" ")}
                </Label>
              </div>
            ))}
          </div>
        </Modal.Body>
        <Modal.Footer>
          <Button color="blue" onClick={() => resendAll({ sms_type: smsType })}>
            {isPending && (
              <Spinner
                aria-label="Spinner button example"
                size="xs"
                className="mr-1"
              />
            )}
            Resend SMS
          </Button>
        </Modal.Footer>
      </Modal>
      <ActionButton type="any" onClick={() => setOpen(true)}>
        <div className="flex">
          <div className="mt-1">
            {!isPending ? (
              <HiOutlineRefresh />
            ) : (
              <div className="-mt-1 mr-1">
                <Spinner size="xs" />
              </div>
            )}
          </div>
          <div className="ml-1">Resend All</div>
        </div>
      </ActionButton>
    </div>
  );
};

export default SmsResendAll;
