import React from "react";
import { toast, ToastOptions, TypeOptions } from "react-toastify";
import { checkIsMobile } from "../utils/checkIsMobile";
import { useDarkMode } from "./useDarkMode";

type ToastType = TypeOptions;

export const useToast = () => {
  const isMobile = checkIsMobile();
  const [isDark] = useDarkMode();

  return (
    text: string,
    type: ToastType = "default",
    options: ToastOptions = {
      position: "top-center",
      draggable: true,
      theme: isMobile ? (isDark ? "dark" : "light") : "colored",
      rtl: true,
      autoClose: isMobile ? 2000 : 3000,
      style: {
        width: isMobile ? "100vw" : text?.length <= 45 ? "400px" : "450px",
      },
    }
  ) => {
    toast(text, { type, ...options });
  };
};

export const useConfirmToast = () => {
  const isMobile = checkIsMobile();
  const [isDark] = useDarkMode();

  return (
    text: string,
    options: ToastOptions = {
      position: "top-center",
      draggable: true,
      theme: isMobile ? (isDark ? "dark" : "light") : "colored",
      rtl: true,
      autoClose: false,
      closeOnClick: false,
      style: {
        width: isMobile ? "100vw" : text?.length <= 45 ? "400px" : "450px",
      },
    }
  ): Promise<boolean> => {
    return new Promise((resolve) => {
      const ConfirmToast = () =>
        React.createElement(
          "div",
          { className: "flex flex-col gap-3 p-2" },
          React.createElement("p", { className: "text-sm" }, text),
          React.createElement(
            "div",
            { className: "flex gap-2 justify-end" },
            React.createElement(
              "button",
              {
                onClick: () => {
                  toast.dismiss();
                  resolve(false);
                },
                className:
                  "px-4 py-2 text-sm rounded-md bg-gray-200 text-gray-700 transition-colors cursor-pointer hover:shadow",
              },
              "انصراف"
            ),
            React.createElement(
              "button",
              {
                onClick: () => {
                  toast.dismiss();
                  resolve(true);
                },
                className:
                  "px-4 py-2 text-sm rounded-md bg-primary-600 text-white transition-colors cursor-pointer hover:shadow",
              },
              "تایید"
            )
          )
        );

      toast(React.createElement(ConfirmToast), {
        type: "error",
        ...options,
      });
    });
  };
};
