import React, { useEffect, useRef, useState } from "react";
import style from "./addAddressBox.module.css";
import InputText from "../utils/inputText";
import SearchSelect from "../utils/searchSelect";
import { managerApi, customerApi } from "@/api/api";
import { CancelToken } from "axios";
import { usePhoneValidation } from "@/customHook/useValidation";
import Loader from "../utils/loader";
import OverlayBox from "@/components/utils/others/overlayBox";
import { createNotification } from "@/customHook/useNotification";

const AddAddressBox = (props) => {
  const [btnLoader, setBtnLoader] = useState(false);
  const defaultStructure = {
    name: "",
    addressline_1: "",
    addressline_2: "",
    landmark: "",
    country: "",
    state: "",
    phone: "",
    zip_code: "",
    dial_code: "",
  };
  const [newAddAddress, setNewAddAddress] = useState({
    ...defaultStructure,
  });
  const addNewPhoneValidation = usePhoneValidation(newAddAddress.phone);
  const [addErrorList, setAddErrorList] = useState({
    ...defaultStructure,
  });
  const [countrySelectOption, setCountrySelectOption] = useState([]);
  const [stateSelectOption, setStateSelectOption] = useState([]);
  const [stateLoader, setStateLoader] = useState(true);
  const source = CancelToken.source();
  const ref = useRef();

  const onSubmitNewAddress = async () => {
    await customerApi
      .post("/address", { ...newAddAddress })
      .then((res) => {
        if (res.data.success == true) {
          props.loadAddress();
          createNotification("success", "Address Updated Successfully");
        } else {
          createNotification("error", "Failed To Add");
        }
        setBtnLoader(false);
        props.close();
        setNewAddAddress({ ...defaultStructure });
      })
      .catch((err) => {
        console.log(err);
        setBtnLoader(false);
        createNotification("error", "Failed To Add");
      });
  };

  const loadStateData = async (country) => {
    setStateLoader(true);
    setStateSelectOption([]);
    setNewAddAddress((prev) => {
      let newObject = { ...prev };
      newObject.state = null;
      return newObject;
    });
    await managerApi
      .get("/customer/states?country=" + country, {
        cancelToken: source.token,
      })
      .then((res) => {
        setStateSelectOption(() => {
          let newArray = [];
          if (res.data.data.length > 0)
            for (const item of res.data.data) {
              newArray.push({
                title: item.name,
                value: item.name.toLowerCase(),
              });
            }
          return newArray;
        });
        setStateLoader(false);
      })
      .catch((err) => {
        console.log(err);
        setStateLoader(false);
      });
  };

  const loadCountryData = async (searchValue = "") => {
    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;
        });
      })
      .catch((err) => {
        console.log(err);
      });
  };

  useEffect(() => {
    if (newAddAddress.phone)
      setAddErrorList((prev) => {
        let newObject = { ...prev };
        newObject.phone = !addNewPhoneValidation.value;
        return newObject;
      });
    else
      setAddErrorList((prev) => {
        let newObject = { ...prev };
        newObject.phone = false;
        return newObject;
      });
  }, [addNewPhoneValidation.value]);

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

  const submitAddHandler = (e) => {
    e.preventDefault();
    setBtnLoader(true);
    let errorFound = false;
    console.log("newAddAddress", newAddAddress);
    for (const item in newAddAddress) {
      if (item == "zip_code" || item == "landmark" || item == "_id") continue;
      if (!newAddAddress[item]) {
        setAddErrorList((prev) => {
          let newObject = { ...prev };
          newObject[item] = true;
          return newObject;
        });
        errorFound = true;
        console.log("error: found", item);
      } else {
        setAddErrorList((prev) => {
          let newObject = { ...prev };
          newObject[item] = false;
          return newObject;
        });
      }
    }
    if (addNewPhoneValidation.value == false) {
      setAddErrorList((prev) => {
        let newObject = { ...prev };
        newObject["phone"] = true;
        return newObject;
      });
      errorFound = true;
    }
    console.log("error: found phone");
    if (errorFound === false) {
      onSubmitNewAddress();
    } else {
      setBtnLoader(false);
    }
  };

  return (
    <OverlayBox
      open={props.open}
      close={() => {
        props.close();
      }}
      title={"Add New Address"}
      customClass={style.customClass}
    >
      <form onSubmit={submitAddHandler}>
        <div className={style.selectBox}>
          <div>
            <p>Full Name</p>
            <InputText
              placeholder="Enter name"
              getValue={(value) => {
                setNewAddAddress((prev) => {
                  let newObject = { ...prev };
                  newObject.name = value;
                  return newObject;
                });
                if (value) {
                  setAddErrorList((prev) => {
                    let newObject = { ...prev };
                    newObject.name = false;
                    return newObject;
                  });
                }
              }}
              required={true}
              error={addErrorList.name}
              value={newAddAddress.name}
              customClass={style.customInputClass}
            />
          </div>
          <div>
            <p>Address Line 1</p>
            <InputText
              placeholder="Enter address"
              getValue={(value) => {
                setNewAddAddress((prev) => {
                  let newObject = { ...prev };
                  newObject.addressline_1 = value;
                  return newObject;
                });
                if (value) {
                  setAddErrorList((prev) => {
                    let newObject = { ...prev };
                    newObject.addressline_1 = false;
                    return newObject;
                  });
                }
              }}
              required={true}
              error={addErrorList.addressline_1}
              value={newAddAddress.addressline_1}
              customClass={style.customInputClass}
            />
          </div>
          <div>
            <p>Address Line 2</p>
            <InputText
              placeholder="Enter address"
              getValue={(value) => {
                setNewAddAddress((prev) => {
                  let newObject = { ...prev };
                  newObject.addressline_2 = value;
                  return newObject;
                });
                if (value) {
                  setAddErrorList((prev) => {
                    let newObject = { ...prev };
                    newObject.addressline_2 = false;
                    return newObject;
                  });
                }
              }}
              required={true}
              error={addErrorList.addressline_2}
              value={newAddAddress.addressline_2}
              customClass={style.customInputClass}
            />
          </div>
          <div>
            <p>Landmark</p>
            <InputText
              placeholder="Enter landmark"
              getValue={(value) => {
                setNewAddAddress((prev) => {
                  let newObject = { ...prev };
                  newObject.landmark = value;
                  return newObject;
                });
              }}
              error={addErrorList.landmark}
              value={newAddAddress.landmark}
              customClass={style.customInputClass}
            />
          </div>
          <div>
            <p>Country </p>
            <SearchSelect
              setOption={countrySelectOption}
              placeholder={`Select Country`}
              setSearchPlaceholder={"Search Country"}
              getValue={(value) => {
                console.log("value: ", value);
                setNewAddAddress((prev) => {
                  let newObject = { ...prev };
                  newObject["country"] = value.value;
                  newObject["dial_code"] = value.dial_code;
                  return newObject;
                });
                setNewAddAddress((prev) => {
                  let newObject = { ...prev };
                  newObject.state = "";
                  return newObject;
                });
                loadStateData(value.value);
                if (value) {
                  setAddErrorList((prev) => {
                    let newObject = { ...prev };
                    newObject.country = false;
                    return newObject;
                  });
                }
              }}
              error={addErrorList.country}
              setValue={newAddAddress.country}
              customCss={`${style.custom_css_select}`}
              customCssForBtn={style.customCssBtn}
            />
          </div>
          {newAddAddress.country && (
            <>
              <div>
                <p>Emirate </p>
                <SearchSelect
                  setOption={stateSelectOption}
                  placeholder={`Select Emirate`}
                  getValue={(value) => {
                    if (value.value)
                      setNewAddAddress((prev) => {
                        let newObject = { ...prev };
                        newObject["state"] = value.value;
                        return newObject;
                      });
                    if (value.value) {
                      setAddErrorList((prev) => {
                        let newObject = { ...prev };
                        newObject.state = false;
                        return newObject;
                      });
                    }
                  }}
                  error={addErrorList.state}
                  loader={stateLoader}
                  setValue={newAddAddress.state}
                  customCss={`${style.custom_css_select}`}
                  customCssForBtn={style.customCssBtn}
                />
              </div>
            </>
          )}
          <div>
            <p>Mobile No</p>
            <div className={style.flex_phone}>
              {newAddAddress.dial_code && (
                <div className={style.dial_code}>
                  +{newAddAddress.dial_code}
                </div>
              )}
              <InputText
                type="tel"
                placeholder="Enter mobile no"
                maxLength={10}
                minLength={5}
                getValue={(value) => {
                  setNewAddAddress((prev) => {
                    let newObject = { ...prev };
                    newObject.phone = value;
                    return newObject;
                  });
                  if (value) {
                    setAddErrorList((prev) => {
                      let newObject = { ...prev };
                      newObject.phone = false;
                      return newObject;
                    });
                  }
                }}
                required={true}
                error={addErrorList.phone}
                value={newAddAddress.phone}
                customClass={style.customInputClass}
              />
            </div>
          </div>
        </div>
        <div className={style.overLayFooter}>
          <div
            className={`secondary-btn ${style.customBtn}`}
            onClick={() => {
              props.close();
              setNewAddAddress({ ...defaultStructure });
            }}
          >
            Cancel
          </div>
          {btnLoader ? (
            <div className={`primary_btn_no_animation ${style.customBtn}`}>
              <Loader className={style.btnLoader} />
            </div>
          ) : (
            <button
              type="submit"
              className={`primary_btn_no_animation ${style.customBtn}`}
            >
              Add
            </button>
          )}
        </div>
      </form>
    </OverlayBox>
  );
};

export default AddAddressBox;
