import InputText from "./inputText";
import OverlayBox from "./others/overlayBox";
import style from "./subscribeInput.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 SubscribeInput = (props) => {
  const [subscriberEmail, setSubscriberEmail] = useState();
  const [loader, setLoader] = useState(false);
  const [refreshReCaptcha, setRefreshReCaptcha] = useState(false);
  const [captcha, setCaptcha] = useState();
  const emailValidation = useEmailValidation(subscriberEmail);

  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;
        }
        createNotification("success", "Email Added To Subscriber List");
        setLoader(false);
        setRefreshReCaptcha((prev) => !prev);
      })
      .catch((err) => {
        console.log(err);
        setLoader(false);
        setRefreshReCaptcha((prev) => !prev);
      });
  };

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

  return (
    <form className={style.subscribe_section} onSubmit={submitHandler}>
      <InputText
        type="email"
        placeholder="Enter 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={`secondary-btn ${style.subscribe_btn}`}
          type="submit"
        >
          Subscribe
        </button>
      )}
    </form>
  );
};

export default SubscribeInput;
