import React, { useEffect, useState } from "react";
import style from "./profile.module.css";
import NavbarAccount from "@/components/account/navbarAccount";
import InputText from "../../components/utils/inputText";
import SearchSelect from "../../components/utils/searchSelect";
import { managerApi, customerApi, authApi } from "@/api/api";
import { CancelToken } from "axios";
import {
  usePhoneValidation,
  useEmailValidation,
} from "@/customHook/useValidation";
import Loader from "@/components/utils/loader";
import { createNotification } from "@/customHook/useNotification";
import ConfirmBox from "@/components/utils/confirmBox";
import { confirmAlert } from "react-confirm-alert";
import { useSelector } from "react-redux";
import { useRouter } from "next/router";
import ResetPassword from "@/components/account/profile/resetPassword";
import {
  ArrowBack,
  ManageAccountsOutlined,
  RefreshOutlined,
} from "@mui/icons-material";
import Head from "next/head";

const Profile = () => {
  const [loader, setLoader] = useState(true);
  const [resetOpen, setResetOpen] = useState(false);
  const [btnLoader, setBtnLoader] = useState(false);
  const [countryLoader, setCountryLoader] = useState(true);
  const [dialCode, setDialCode] = useState();
  const defaultStructure = {
    name: "",
    country: "",
    phone: "",
    email: "",
    _id: "",
    dial_code: "",
    whatsapp_number: "",
  };
  const router = useRouter();
  const accountLogin = useSelector((state) => state.accountStore.loggedIn);
  useEffect(() => {
    loadCountryData();
    loadUserData();
  }, []);
  const [profileData, setProfileData] = useState({
    ...defaultStructure,
  });
  const phoneValidation = usePhoneValidation(profileData.phone);
  const emailValidation = useEmailValidation(profileData.email);
  const [errorList, setErrorList] = useState({
    ...defaultStructure,
  });
  const [countrySelectOption, setCountrySelectOption] = useState([]);
  const source = CancelToken.source();

  const loadUserData = async () => {
    setLoader(true);
    await customerApi
      .get("/user")
      .then((res) => {
        setProfileData((prev) => {
          let newArray = {
            ...prev,
            name: res.data.data.name,
            country: res.data.data.country,
            dial_code: res.data.data.dial_code,
            phone: res.data.data.phone,
            email: res.data.data.email,
            _id: res.data.data._id,
            whatsapp_number: res.data.data.whatsapp_number,
          };
          return newArray;
        });
        setLoader(false);
        console.log("res.data: ", res.data);
      })
      .catch((err) => {
        console.log(err);
        setLoader(false);
      });
  };

  const onSubmitprofileData = async () => {
    await customerApi
      .post("/user", { ...profileData })
      .then((res) => {
        if (res.data.success == true) {
          createNotification("success", "Profile Updated Successfully");
        } else {
          createNotification("error", "Failed To Update");
        }
        setBtnLoader(false);
      })
      .catch((err) => {
        console.log(err);
        setBtnLoader(false);
        createNotification("error", "Failed To Update");
      });
  };

  const loadCountryData = async (searchValue = "") => {
    setCountryLoader(true);
    await managerApi
      .get("/customer/country?search=" + searchValue, {
        cancelToken: source.token,
      })
      .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 submitHandler = (e) => {
    e.preventDefault();
    setBtnLoader(true);
    let errorFound = false;
    for (const item in profileData) {
      if (item === "whatsapp_number") continue;
      if (!profileData[item]) {
        setErrorList((prev) => {
          let newObject = { ...prev };
          newObject[item] = true;
          return newObject;
        });
        errorFound = true;
      } else {
        setErrorList((prev) => {
          let newObject = { ...prev };
          newObject[item] = false;
          return newObject;
        });
      }
    }
    if (phoneValidation.value == false) {
      setErrorList((prev) => {
        let newObject = { ...prev };
        newObject["phone"] = true;
        return newObject;
      });
      errorFound = true;
    }
    if (emailValidation.value == false) {
      setErrorList((prev) => {
        let newObject = { ...prev };
        newObject["email"] = true;
        return newObject;
      });
      errorFound = true;
    }
    if (errorFound === false) {
      onSubmitprofileData();
    } else {
      setBtnLoader(false);
    }
  };

  return (
    <React.Fragment>
      <Head>
        <title>Profile</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      </Head>
      <div className={`account_header container`}>
        <div className={`account_header_flex`}>
          <div className={`account_header_flex_back_btn`}>
            <button
              type="button"
              className={`secondary-btn`}
              onClick={() => router.push("/account")}
            >
              <ArrowBack />
            </button>
            <button
              type="button"
              className={`secondary-btn`}
              onClick={() => loadUserData()}
            >
              <RefreshOutlined />
            </button>
          </div>
          <div className={`account_header_flex_title`}>
            <ManageAccountsOutlined />
            Profile
          </div>
        </div>
        <hr></hr>
      </div>
      {loader && <Loader className={style.loader} />}
      {!loader && (
        <div className="container mb-3">
          <div className={`${style.address_section}`}>
            <div className={style.overLayFooter}>
              <button
                type="button"
                className={`secondary-btn ${style.customBtn}`}
                onClick={() => setResetOpen(true)}
              >
                Reset Password
              </button>
            </div>
            <div className={style.section_data}>
              <form onSubmit={submitHandler}>
                <div className={style.selectBox}>
                  <div>
                    <p>Name</p>
                    <InputText
                      placeholder="Enter name"
                      getValue={(value) => {
                        setProfileData((prev) => {
                          let newObject = { ...prev };
                          newObject.name = value;
                          return newObject;
                        });
                        if (value) {
                          setErrorList((prev) => {
                            let newObject = { ...prev };
                            newObject.name = false;
                            return newObject;
                          });
                        }
                      }}
                      required={true}
                      error={errorList.name}
                      value={profileData.name}
                      customClass={style.customInputClass}
                    />
                  </div>
                  <div>
                    <p>Email</p>
                    <InputText
                      type="email"
                      placeholder="Enter email address"
                      getValue={(value) => {
                        setProfileData((prev) => {
                          let newObject = { ...prev };
                          newObject.email = value;
                          return newObject;
                        });
                        if (value) {
                          setErrorList((prev) => {
                            let newObject = { ...prev };
                            newObject.email = false;
                            return newObject;
                          });
                        }
                      }}
                      required={true}
                      error={errorList.email}
                      value={profileData.email}
                      customClass={style.customInputClass}
                    />
                  </div>
                  <div>
                    <p>Country </p>
                    <SearchSelect
                      setOption={countrySelectOption}
                      placeholder={`Select Country`}
                      setSearchPlaceholder={"Search Country"}
                      getValue={(value) => {
                        console.log("value: ", value);
                        setProfileData((prev) => {
                          let newObject = { ...prev };
                          newObject["country"] = value.value;
                          newObject["dial_code"] = value.dial_code;
                          return newObject;
                        });
                        if (value) {
                          setErrorList((prev) => {
                            let newObject = { ...prev };
                            newObject.country = false;
                            return newObject;
                          });
                        }
                      }}
                      loader={countryLoader}
                      error={errorList.country}
                      setValue={profileData.country}
                      customCss={`${style.custom_css_select}`}
                      customCssForBtn={style.customCssBtn}
                    />
                  </div>
                  <div>
                    <p>Mobile No</p>
                    <div className={style.flex_phone}>
                      {profileData.dial_code && (
                        <div className={style.dial_code}>
                          +{profileData.dial_code}
                        </div>
                      )}
                      <InputText
                        type="tel"
                        placeholder="Enter mobile no"
                        maxLength={10}
                        minLength={5}
                        getValue={(value) => {
                          setProfileData((prev) => {
                            let newObject = { ...prev };
                            newObject.phone = value;
                            return newObject;
                          });
                          if (value) {
                            setErrorList((prev) => {
                              let newObject = { ...prev };
                              newObject.phone = false;
                              return newObject;
                            });
                          }
                        }}
                        required={true}
                        error={errorList.phone}
                        value={profileData.phone}
                        customClass={style.customInputClass}
                      />
                    </div>
                  </div>
                  <div>
                    <p>Whatsapp No</p>
                    <div className={style.flex_phone}>
                      {profileData.dial_code && (
                        <div className={style.dial_code}>
                          +{profileData.dial_code}
                        </div>
                      )}
                      <InputText
                        type="tel"
                        placeholder="Enter whatsapp number"
                        maxLength={10}
                        minLength={5}
                        getValue={(value) => {
                          setProfileData((prev) => {
                            let newObject = { ...prev };
                            newObject.whatsapp_number = value;
                            return newObject;
                          });
                        }}
                        value={profileData.whatsapp_number}
                        customClass={style.customInputClass}
                      />
                    </div>
                  </div>
                </div>
                <div className={style.overLayFooter}>
                  {btnLoader ? (
                    <div
                      className={`teritary_btn ${style.customBtn}`}
                    >
                      <Loader className={style.btnLoader} />
                    </div>
                  ) : (
                    <button
                      type="submit"
                      className={`teritary_btn ${style.customBtn}`}
                    >
                      Submit
                    </button>
                  )}
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
      {resetOpen && (
        <ResetPassword open={resetOpen} close={() => setResetOpen(false)} />
      )}
    </React.Fragment>
  );
};

export default Profile;
