import InputText from "../utils/inputText";
import OverlayBox from "../utils/others/overlayBox";
import style from "./popupMessage.module.css";
import { authApi, customerApi, managerApi } from "@/api/api";
import { useCallback, useEffect, useRef, useState } from "react";
import { createNotification } from "@/customHook/useNotification";
import { useEmailValidation } from "@/customHook/useValidation";
import Loader from "@/components/utils/btnLoader";
import HtmlParser from "react-html-parser";
import NextImage from "@/other/NextImage";
import { GoogleReCaptcha } from "react-google-recaptcha-v3";

const PopupMessage = (props) => {
  const [popupCode, setPopupCode] = useState();
  const [popupData, setPopupData] = useState({});
  const [error, setError] = useState("");
  const [subscriberEmail, setSubscriberEmail] = useState();
  const [loader, setLoader] = useState(false);
  const [refreshReCaptcha, setRefreshReCaptcha] = useState(false);
  const [captcha, setCaptcha] = useState();
  const emailValidation = useEmailValidation(subscriberEmail);
  const [popupOpen, setPopupOpen] = useState(false);

  const loadPopup = async () => {
    await customerApi
      .get("/popup/message")
      .then((res) => {
        console.log("popup:", res.data);
        if (
          res.data.success === true &&
          (res.data.data.title || res.data.data.description)
        ) {
          setPopupData(res.data.data);
          setPopupOpen(true);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const submitHandler = async (e) => {
    e.preventDefault();
    if (!captcha) {
      createNotification("error", "Complete Recaptcha");
      return;
    }
    setLoader(true);
    if (emailValidation.value === false) {
      createNotification("error", "Invalid Email Format!");
      setLoader(false);
      return;
    }
    await customerApi
      .post("/email/subscriber", { email: subscriberEmail, token: captcha })
      .then((res) => {
        console.log("subscriber:", res.data);
        if (
          res.data &&
          res.data.message &&
          res.data.message.toLowerCase() === "recaptcha failed"
        ) {
          createNotification("error", "Recaptcha Failed!");
          setLoader(false);
          return;
        }
        setPopupOpen(false);
        createNotification("success", "Email Added To Subscriber List");
        localStorage.setItem("popup", popupData.code);
        setLoader(false);
        setRefreshReCaptcha((prev) => !prev);
      })
      .catch((err) => {
        console.log(err);
        setLoader(false);
        setRefreshReCaptcha((prev) => !prev);
      });
  };

  useEffect(() => {
    setPopupCode(localStorage.getItem("popup"));
    loadPopup();
    console.log("test");
  }, []);

  const onVerify = useCallback((token) => {
    setCaptcha(token);
  }, []);

  return (
    <OverlayBox
      open={popupCode === popupData.code ? false : popupOpen}
      close={(value) => {
        setPopupOpen(false);
        localStorage.setItem("popup", popupData.code);
      }}
      head={false}
      blur={true}
      disableOverlayClose={true}
      customClass={style.customOverlayClass}
      customMainClass={style.customMainClass}
      customBodyClass={style.customBodyClass}
    >
      <div className={`${style.popupMessage} ql-editor`}>
        <div
          className={`${style.top_section} ${
            popupData.image ? "" : style.noImage
          }`}
        >
          <div className={style.text_body}>
            {popupData.title && (
              <div className={style.title}>{popupData.title}</div>
            )}
            {popupData.description && (
              <div className={style.subtext}>
                {HtmlParser(popupData.description)}
              </div>
            )}
            {popupData.button_text && popupData.button_path && (
              <button
                className={`secondary-btn ${style.primary_btn}`}
                onClick={() => {
                  if (popupData.button_path.includes("http")) {
                    window.open(popupData.button_path, "_blank");
                  } else {
                    router.push(popupData.button_path);
                  }
                }}
              >
                {popupData.button_text}
              </button>
            )}
            {popupData.email_subscription && (
              <form
                className={style.subscribe_section}
                onSubmit={submitHandler}
              >
                <InputText
                  type="email"
                  placeholder="Email"
                  getValue={(value) => {
                    setSubscriberEmail(value);
                  }}
                  require={true}
                />
                <GoogleReCaptcha
                  onVerify={onVerify}
                  refreshReCaptcha={refreshReCaptcha}
                />
                {loader ? (
                  <button
                    type="button"
                    className={`primary_btn_no_animation ${style.subscribe_btn}`}
                    disabled={true}
                  >
                    <Loader className={style.loader} />
                  </button>
                ) : (
                  <button
                    className={`primary_btn_no_animation ${style.subscribe_btn}`}
                    type="submit"
                  >
                    Subscribe
                  </button>
                )}
                <button
                  type="button"
                  className={`secondary-btn ${style.secondary_btn}`}
                  onClick={() => {
                    setPopupOpen(false);
                    localStorage.setItem("popup", popupData.code);
                  }}
                >
                  No Thanks
                </button>
              </form>
            )}
          </div>
          {popupData.image && (
            <div className={style.image_body}>
              <NextImage
                src={
                  process.env.NEXT_PUBLIC_UPLOADS +
                  "/popup_message/" +
                  popupData.image
                }
                alt="Popup Image"
                className={style.image}
              />
            </div>
          )}
        </div>
      </div>
    </OverlayBox>
  );
};

export default PopupMessage;
