import InputText from "../../utils/inputText";
import OverlayBox from "../../utils/others/overlayBox";
import style from "./signUp.module.css";
import { Email, Key, Person, Phone } from "@mui/icons-material";
import { useDispatch, useSelector } from "react-redux";
import { accountStoreActions } from "@/store/account";
import { authApi, customerApi, managerApi } from "@/api/api";
import { useCallback, useEffect, useRef, useState } from "react";
import { createNotification } from "@/customHook/useNotification";
import SearchSelect from "@/components/utils/searchSelect";
import jwtDecode from "jwt-decode";
import ReCAPTCHA from "react-google-recaptcha";
import { loadCart, loadWishlist } from "@/store/index";
import {
  usePhoneValidation,
  usePasswordValidation,
  useEmailValidation,
} from "@/customHook/useValidation";
import Loader from "@/components/utils/loader";
import { GoogleReCaptcha } from "react-google-recaptcha-v3";

const SignUp = (props) => {
  const signUpUI = useSelector((state) => state.accountStore.signUpUI);
  const dispatch = useDispatch();
  const [loader, setLoader] = useState(false);
  const [error, setError] = useState("");
  const [refreshReCaptcha, setRefreshReCaptcha] = useState(false);
  const [captcha, setCaptcha] = useState();
  const [dialCode, setDialCode] = useState();
  const [signUpData, setSignUpData] = useState({
    name: "",
    email: "",
    password: "",
    country: "",
    dial_code: "",
    phone: "",
    whatsapp_number: "",
    subscribe: false,
  });
  const phoneValidation = usePhoneValidation(signUpData.phone);
  const whatsappValidation = usePhoneValidation(signUpData.whatsapp_number);
  const emailValidation = useEmailValidation(signUpData.email);
  const passwordValidation = usePasswordValidation(signUpData.password);
  const [regError, setRegError] = useState({
    name: false,
    email: false,
    country: false,
    password: false,
    phone: false,
    whatsapp_number: false,
    dial_code: false,
  });
  const [regWarn, setRegWarn] = useState(null);
  const [regLoader, setRegLoader] = useState(false);

  const [countrySelectOption, setCountrySelectOption] = useState([]);
  const [countryLoader, setCountryLoader] = useState(true);

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

  const loadCountryData = async (searchValue = "") => {
    setCountryLoader(true);
    await managerApi
      .get("/customer/all/country")
      .then((res) => {
        setCountrySelectOption(() => {
          let newArray = [];
          if (res.data.data.length > 0)
            for (const item of res.data.data) {
              newArray.push({
                title: item.name,
                value: item.name.toLowerCase(),
                dial_code: item.phone_code,
              });
            }
          return newArray;
        });
        setCountryLoader(false);
      })
      .catch((err) => {
        setCountryLoader(false);
        console.log(err);
      });
  };

  const registerSubmitHandler = async (e) => {
    e.preventDefault();
    if (!captcha) {
      setError("Complete Captcha!");
      return 0;
    }
    setRegWarn(null);
    setRegLoader(true);
    console.log("signUpData, ", signUpData);
    let errorFound = false;

    if (!signUpData.country) {
      setRegError((prev) => {
        let errorObject = { ...prev };
        errorObject.country = true;
        return errorObject;
      });
      errorFound = true;
    } else {
      setRegError((prev) => {
        let errorObject = { ...prev };
        errorObject.country = false;
        return errorObject;
      });
    }
    if (!emailValidation.value) {
      setRegError((prev) => {
        let errorObject = { ...prev };
        errorObject.email = true;
        return errorObject;
      });
      errorFound = true;
    } else {
      setRegError((prev) => {
        let errorObject = { ...prev };
        errorObject.email = false;
        return errorObject;
      });
    }
    if (!phoneValidation.value) {
      setRegError((prev) => {
        let errorObject = { ...prev };
        errorObject.phone = true;
        return errorObject;
      });
      errorFound = true;
      createNotification("error", "Wrong phone number format");
      setRegLoader(false);
      return;
    } else {
      setRegError((prev) => {
        let errorObject = { ...prev };
        errorObject.phone = false;
        return errorObject;
      });
    }

    console.log("signUpData.whatsapp_number", signUpData.whatsapp_number);
    if (signUpData.whatsapp_number) {
      if (!whatsappValidation.value) {
        setRegError((prev) => {
          let errorObject = { ...prev };
          errorObject.whatsapp_number = true;
          return errorObject;
        });
        errorFound = true;
        createNotification("error", "Incorrect Whatsapp Number Format");
        setRegLoader(false);
        return;
      } else {
        setRegError((prev) => {
          let errorObject = { ...prev };
          errorObject.whatsapp_number = false;
          return errorObject;
        });
      }
    }
    if (!passwordValidation.value) {
      setRegError((prev) => {
        let errorObject = { ...prev };
        errorObject.password = true;
        return errorObject;
      });
      errorFound = true;
      createNotification("error", "Incorrect Password Format");
      setRegLoader(false);
      return;
    } else {
      setRegError((prev) => {
        let errorObject = { ...prev };
        errorObject.password = false;
        return errorObject;
      });
    }

    if (errorFound === false) {
      await authApi
        .post("/customer", {
          ...signUpData,
          token: captcha,
        })
        .then((res) => {
          console.log(":res.status ", res.status);
          if (res.data.success === true) {
            dispatch(accountStoreActions.closeSignUpUI());
            props.setRegisterSuccessOpen(true);
          } else {
            setError("Registration Failed!!!");
            setRefreshReCaptcha((prev) => !prev);
          }
          setRegLoader(false);
        })
        .catch((err) => {
          console.log("err: ", err);
          if (err.response.status === 409) {
            setError("User Already Exist!!!");
          } else {
            setError("Registration Failed!!!");
          }
          setRefreshReCaptcha((prev) => !prev);
          setRegLoader(false);
        });
    } else {
      createNotification("error", "Complete Required Fields!!");
      setRegLoader(false);
    }
  };

  useEffect(() => {
    loadCountryData();
  }, []);

  useEffect(() => {
    console.log("signUpData", signUpData);
  }, [signUpData]);

  return (
    <OverlayBox
      open={signUpUI}
      close={(value) => {
        setLoader(false);
        setRegWarn(null);
        setRegError({
          name: false,
          email: false,
          country: false,
          password: false,
          phone: false,
          whatsapp_number: false,
        });
        dispatch(accountStoreActions.closeSignUpUI());
      }}
      title="Account"
      head={true}
      blur={true}
      customClass={style.customOverlayClass}
    >
      <div className={style.signIn_form}>
        <div className={style.section_box}>
          <form onSubmit={registerSubmitHandler}>
            <div className={style.input_section}>
              <InputText
                type="text"
                name="name"
                icon={<Person />}
                placeholder="Name"
                getValue={(value) => {
                  if (value) {
                    setSignUpData((prev) => {
                      let newObject = { ...prev };
                      newObject.name = value;
                      return newObject;
                    });
                  }
                }}
                required={true}
                error={regError.name}
                label={"Full Name"}
                customClass={style.customInputClass}
              />
              <InputText
                type="email"
                name="email"
                icon={<Email />}
                placeholder="Email"
                getValue={(value) => {
                  setSignUpData((prev) => {
                    let newObject = { ...prev };
                    newObject.email = value;
                    return newObject;
                  });
                }}
                required={true}
                error={regError.email}
                label={"Email"}
                customClass={style.customInputSignUpClass}
              />
              <InputText
                type="password"
                name="password"
                icon={<Key />}
                placeholder="Password"
                label={"Password"}
                getValue={(value) => {
                  setSignUpData((prev) => {
                    let newObject = { ...prev };
                    newObject.password = value;
                    return newObject;
                  });
                }}
                required={true}
                error={regError.password}
                message="Atleast one special character, one numeric, one capital letter, 10 minimum length & maximum 20 length"
                customClass={style.customInputSignUpClass}
              />
              <SearchSelect
                setOption={countrySelectOption}
                placeholder={`Select Country`}
                setSearchPlaceholder={"Search Country"}
                loader={countryLoader}
                getValue={(value) => {
                  console.log("value: ", value);
                  if (value) {
                    setSignUpData((prev) => {
                      let newObject = { ...prev };
                      newObject.country = value.value;
                      newObject.dial_code = value.dial_code;
                      return newObject;
                    });
                  }
                }}
                error={regError.country}
                setValue={signUpData.country}
                customCssForBtn={`${style.customCssBtn}`}
              />
              {signUpData.dial_code && (
                <div className={style.flex_phone}>
                  {signUpData.dial_code && (
                    <div className={style.dial_code}>
                      +{signUpData.dial_code}
                    </div>
                  )}
                  <InputText
                    type="tel"
                    name="phone"
                    maxLength={10}
                    minLength={5}
                    icon={<Phone />}
                    placeholder="Phone Number"
                    getValue={(value) => {
                      console.log("value: ", value);

                      setSignUpData((prev) => {
                        let newObject = { ...prev };
                        newObject.phone = value;
                        return newObject;
                      });
                    }}
                    required={true}
                    error={regError.phone}
                    label={"Phone Number"}
                    customClass={style.customInputSignUpClass}
                  />
                </div>
              )}
              {signUpData.dial_code && (
                <div className={style.flex_phone}>
                  {signUpData.dial_code && (
                    <div className={style.dial_code}>
                      +{signUpData.dial_code}
                    </div>
                  )}
                  <InputText
                    type="tel"
                    name="phone"
                    maxLength={10}
                    minLength={5}
                    icon={<Phone />}
                    placeholder="Whatsapp Number"
                    getValue={(value) => {
                      setSignUpData((prev) => {
                        let newObject = { ...prev };
                        newObject.whatsapp_number = value;
                        return newObject;
                      });
                    }}
                    error={regError.whatsapp_number}
                    label={"Whatsapp Number"}
                    customClass={style.customInputSignUpClass}
                  />{" "}
                </div>
              )}
              <center>
                <GoogleReCaptcha
                  onVerify={onVerify}
                  refreshReCaptcha={refreshReCaptcha}
                />
              </center>
              <div className={style.subscribe_checkbox}>
                <label for="marketing">
                  <input
                    type="checkbox"
                    onClick={(e) => {
                      console.log("e:", e);
                      setSignUpData((prev) => {
                        let newObject = { ...prev };
                        newObject.subscribe = e.target.checked;
                        return newObject;
                      });
                    }}
                    id="marketing"
                  />{" "}
                  I agree to receive promotions and coupons.
                </label>
              </div>
              <div className={style.status}>
                {error && (
                  <div className={`${style.error_status}`}>{error}</div>
                )}
              </div>
              <button
                type="submit"
                className={`teritary_btn ${style.button} mt-2`}
                disabled={regLoader ? true : false}
              >
                {regLoader ? <Loader className={style.loader} /> : "Sign Up"}
              </button>
            </div>
          </form>
        </div>
        {/* <div className={style.signIn_divider}>
            <hr />
            OR
            <hr />
          </div>
          <div className={style.signIn_with_google}>
            <div className={style.logo}>
              <span />
            </div>
            <div className={style.text_area}>Sign Up With Google</div>
          </div> */}
        <div className={style.signIn_divider}>
          <hr />
          OR
          <hr />
        </div>
        <p
          className={`mb-2 ${style.already_account}`}
          onClick={() => {
            dispatch(accountStoreActions.closeSignUpUI());
            dispatch(accountStoreActions.openSignInUI());
          }}
        >
          Already Have Account
        </p>
      </div>
    </OverlayBox>
  );
};

export default SignUp;
