import InputText from "../utils/inputText";
import style from "./become-a-seller.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 UploadFile from "@/components/utils/uploadFile";
import { Cancel, CheckCircleRounded } from "@mui/icons-material";

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";
import { useRouter } from "next/router";

const BecomeASellerComponent = (props) => {
  const signUpUI = useSelector((state) => state.accountStore.signUpUI);
  const dispatch = useDispatch();
  const [loader, setLoader] = useState(false);
  const [error, setError] = useState("");
  const [captcha, setCaptcha] = useState();
  const [refreshReCaptcha, setRefreshReCaptcha] = useState(false);
  const router = useRouter();
  const [isSuccess, setIsSuccess] = useState(false);
  const [resellerRegisterData, setResellerRegisterData] = useState({
    name: "",
    email: "",
    password: "",
    country: "",
    dial_code: "",
    phone: "",
    whatsapp_number: "",
    id_image: "",
  });
  const phoneValidation = usePhoneValidation(resellerRegisterData.phone);
  const whatsappValidation = usePhoneValidation(
    resellerRegisterData.whatsapp_number
  );
  const emailValidation = useEmailValidation(resellerRegisterData.email);
  const passwordValidation = usePasswordValidation(
    resellerRegisterData.password
  );
  const [regError, setRegError] = useState({
    name: false,
    email: false,
    country: false,
    password: false,
    phone: false,
    whatsapp_number: false,
  });
  const [regWarn, setRegWarn] = useState(null);
  const [regLoader, setRegLoader] = useState(false);

  const [countrySelectOption, setCountrySelectOption] = useState([]);
  const [countryLoader, setCountryLoader] = useState(true);
  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("resellerRegisterData, ", resellerRegisterData);
    let errorFound = false;

    if (!resellerRegisterData.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 (!resellerRegisterData.id_image) {
      setRegError((prev) => {
        let errorObject = { ...prev };
        errorObject.id_image = true;
        return errorObject;
      });
      errorFound = true;
    } else {
      setRegError((prev) => {
        let errorObject = { ...prev };
        errorObject.id_image = 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(
      "resellerRegisterData.whatsapp_number",
      resellerRegisterData.whatsapp_number
    );
    if (resellerRegisterData.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) {
      let formdata = new FormData();
      formdata.append("name", resellerRegisterData.name);
      formdata.append("email", resellerRegisterData.email);
      formdata.append("password", resellerRegisterData.password);
      formdata.append("country", resellerRegisterData.country);
      formdata.append("dial_code", resellerRegisterData.dial_code);
      formdata.append("phone", resellerRegisterData.phone);
      formdata.append("whatsapp_number", resellerRegisterData.whatsapp_number);
      if (resellerRegisterData.id_image)
        formdata.append("id_image", resellerRegisterData.id_image.data);
      formdata.append("token", captcha);
      await authApi
        .post("/reseller", formdata)
        .then((res) => {
          console.log(":res.status ", res.status);
          if (res.data.success === true) {
            setIsSuccess(true);
          } else {
            setError("Registration Failed!!!");
            setRefreshReCaptcha((prev) => !prev);
          }
          setRegLoader(false);
        })
        .catch((err) => {
          console.log("err: ", err);
          if (err.response.status === 409) {
            setError("Already requested for reseller account.");
          } else {
            setError("Registration Failed");
          }
          setRefreshReCaptcha((prev) => !prev);
          setRegLoader(false);
        });
    } else {
      createNotification("error", "Complete Required Fields!!");
      setRegLoader(false);
    }
  };

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

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

  return (
    <div className={style.reseller_form}>
      {!isSuccess ? (
        <div className={style.section_box}>
          <h1>Become A Seller</h1>

          <form onSubmit={registerSubmitHandler}>
            <div className={style.input_section}>
              <InputText
                type="text"
                name="name"
                icon={<Person />}
                placeholder="Name"
                getValue={(value) => {
                  if (value) {
                    setResellerRegisterData((prev) => {
                      let newObject = { ...prev };
                      newObject.name = value;
                      return newObject;
                    });
                  }
                }}
                required={true}
                error={regError.name}
                label={"Full Name"}
                customClass={style.customInputSignUpClass}
              />
              <InputText
                type="email"
                name="email"
                icon={<Email />}
                placeholder="Email"
                getValue={(value) => {
                  setResellerRegisterData((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) => {
                  setResellerRegisterData((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) {
                    setResellerRegisterData((prev) => {
                      let newObject = { ...prev };
                      newObject.country = value.value;
                      newObject.dial_code = value.dial_code;
                      return newObject;
                    });
                  }
                }}
                error={regError.country}
                setValue={resellerRegisterData.country}
                customCssForBtn={`${style.customCssBtn}`}
              />
              {resellerRegisterData.dial_code && (
                <div className={style.flex_phone}>
                  {resellerRegisterData.dial_code && (
                    <div className={style.dial_code}>
                      +{resellerRegisterData.dial_code}
                    </div>
                  )}
                  <InputText
                    type="tel"
                    name="phone"
                    maxLength={10}
                    minLength={5}
                    icon={<Phone />}
                    placeholder="Phone Number"
                    getValue={(value) => {
                      console.log("value: ", value);

                      setResellerRegisterData((prev) => {
                        let newObject = { ...prev };
                        newObject.phone = value;
                        return newObject;
                      });
                    }}
                    required={true}
                    error={regError.phone}
                    label={"Phone Number"}
                    customClass={style.customInputSignUpClass}
                  />
                </div>
              )}
              {resellerRegisterData.dial_code && (
                <div className={style.flex_phone}>
                  {resellerRegisterData.dial_code && (
                    <div className={style.dial_code}>
                      +{resellerRegisterData.dial_code}
                    </div>
                  )}
                  <InputText
                    type="tel"
                    name="phone"
                    maxLength={10}
                    minLength={5}
                    icon={<Phone />}
                    placeholder="Whatsapp Number"
                    getValue={(value) => {
                      setResellerRegisterData((prev) => {
                        let newObject = { ...prev };
                        newObject.whatsapp_number = value;
                        return newObject;
                      });
                    }}
                    error={regError.whatsapp_number}
                    label={"Whatsapp Number"}
                    customClass={style.customInputSignUpClass}
                  />{" "}
                </div>
              )}
              <div className={style.upload_section}>
                <p>Upload ID (Emirates ID/Passport)</p>
                <UploadFile
                  customCss={style.upload_file}
                  maxSize="500"
                  allowedType={[".png", ".jpeg", ".jpg", ".webp", ".pdf"]}
                  error={regError.id_image}
                  getData={(data) => {
                    console.log("data: ", data);
                    setResellerRegisterData((prev) => {
                      let newObject = { ...prev };
                      if (data.data === "deleted") {
                        newObject.id_image = "";
                      } else newObject.id_image = data.data;
                      return newObject;
                    });
                  }}
                  setData={() => {
                    if (resellerRegisterData && resellerRegisterData.id_image) {
                      return resellerRegisterData.id_image;
                    } else return [];
                  }}
                />
              </div>
              <center>
                <GoogleReCaptcha
                  onVerify={onVerify}
                  refreshReCaptcha={refreshReCaptcha}
                />
              </center>
              <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} />
                ) : (
                  "Become A Seller"
                )}
              </button>
            </div>
          </form>
        </div>
      ) : (
        <div>
          <div className={style.section}>
            <div className={style.icon}>
              <CheckCircleRounded />
            </div>
            <p className={style.order_success_text}>Success</p>
            <p>
              We have successfully sent you a confirmation email. Please verify
              your email address to proceed verification process.
            </p>
            {/* <button
              type="button"
              className="secondary-btn"
              onClick={() => router.push("/")}
            >
              Home
            </button> */}
          </div>
        </div>
      )}
    </div>
  );
};

export default BecomeASellerComponent;
