import React, { useEffect, useState } from "react";
import style from "./address.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 } from "@/customHook/useValidation";
import { checkoutStoreActions, validateAddress } from "@/store/checkout";
import {
  ArrowBack,
  Delete,
  Edit,
  MarkEmailUnreadOutlined,
  RefreshOutlined,
} from "@mui/icons-material";
import OverlayBox from "@/components/utils/others/overlayBox";
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 Head from "next/head";

const Address = () => {
  const [openAdd, setOpenAdd] = useState(false);
  const [loader, setLoader] = useState(true);
  const [btnLoader, setBtnLoader] = useState(false);
  const [storedAddress, setStoredAddress] = useState([]);
  const [addressBoxTitle, setAddressBoxTitle] = useState();
  const defaultStructure = {
    name: "",
    addressline_1: "",
    addressline_2: "",
    landmark: "",
    country: "",
    state: "",
    phone: "",
    dial_code: "",
    zip_code: "",
    _id: "",
  };
  const router = useRouter();
  const accountLogin = useSelector((state) => state.accountStore.loggedIn);
  const [newAddress, setNewAddress] = useState({
    ...defaultStructure,
  });
  const phoneValidation = usePhoneValidation(newAddress.phone);
  const [errorList, setErrorList] = useState({
    ...defaultStructure,
  });
  const [countrySelectOption, setCountrySelectOption] = useState([]);
  const [stateSelectOption, setStateSelectOption] = useState([]);
  const [stateLoader, setStateLoader] = useState(true);
  const source = CancelToken.source();

  const loadAddress = async () => {
    setLoader(true);
    setStoredAddress([]);
    setStateSelectOption([]);
    await customerApi
      .get("/addresses?limit=10&page=1")
      .then((res) => {
        if (res.data.result.data.length > 0) {
          setStoredAddress(() => {
            let newArray = [];
            newArray = res.data.result.data.map((item) => {
              return {
                name: item.name,
                addressline_1: item.addressline_1,
                addressline_2: item.addressline_2,
                landmark: item.landmark,
                country: item.country,
                state: item.state,
                dial_code: item.dial_code,
                phone: item.phone,
                zip_code: item.zip_code,
                _id: item._id,
              };
            });
            console.log("newArray: ", newArray);
            return newArray;
          });
        }
        setLoader(false);
      })
      .catch((err) => {
        console.log(err);
        setLoader(false);
      });
  };

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

  const confirmDelete = (id) => {
    confirmAlert({
      customUI: ({ onClose }) => {
        return (
          <ConfirmBox onClose={onClose} onConfirm={() => onDeleteAddress(id)} />
        );
      },
    });
  };

  const onDeleteAddress = async (id) => {
    setLoader(true);
    await customerApi
      .delete("/address", { data: { _id: id } })
      .then((res) => {
        if (res.data.success == true) {
          createNotification("success", "Address Deleted Successfully");
          loadAddress();
        } else {
          createNotification("error", "Failed To Delete");
        }
      })
      .catch((err) => {
        console.log(err);
        createNotification("error", "Failed To Delete");
        setLoader(false);
      });
  };

  const loadStateData = async (country) => {
    setStateLoader(true);
    setStateSelectOption([]);
    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 = "") => {
    setNewAddress((prev) => {
      let newObject = { ...prev };
      newObject.state = null;
      return newObject;
    });
    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(() => {
    loadCountryData();
    loadAddress();
  }, []);
  useEffect(() => {
    if (newAddress.phone)
      setErrorList((prev) => {
        let newObject = { ...prev };
        newObject.phone = !phoneValidation.value;
        return newObject;
      });
    else
      setErrorList((prev) => {
        let newObject = { ...prev };
        newObject.phone = false;
        return newObject;
      });
  }, [phoneValidation.value]);
  useEffect(() => {
    console.log("newAddress: ", newAddress);
    if (newAddress.state) loadStateData(newAddress.country);
  }, [newAddress.country]);

  const submitHandler = (e) => {
    e.preventDefault();
    setBtnLoader(true);
    let errorFound = false;
    for (const item in newAddress) {
      if (item == "zip_code" || item == "landmark" || item == "_id") continue;
      if (!newAddress[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 (errorFound === false) {
      onSubmitNewAddress();
    } else {
      setBtnLoader(false);
    }
  };

  return (
    <React.Fragment>
      <Head>
        <title>Address</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={() => loadAddress()}
            >
              <RefreshOutlined />
            </button>
          </div>
          <div className={`account_header_flex_title`}>
            <MarkEmailUnreadOutlined />
            Addresses
          </div>
        </div>
        <hr></hr>
      </div>
      {loader && <Loader className={style.loader} />}
      {!loader && (
        <div className="container mb-3">
          <div className={`${style.address_section}`}>
            <div className={style.section_data}>
              <div className={style.stored_shipping_address}>
                <div className={style.selectBox}>
                  {storedAddress.map((item, index) => (
                    <div className={`${style.address_box} `} key={item.name}>
                      <p className={style.stored_name}>{item.name}</p>
                      <div className={style.stored_address}>
                        <p>
                          {item.dial_code && `+${item.dial_code}`}
                          {item.phone.replace(/^0+/, "")}
                        </p>
                        <p>{item.addressline_1}</p>
                        <p>{item.addressline_2}</p>
                        {item.landmark && <p>{item.landmark}</p>}
                        {item.zip_code && <p>{item.zip_code}</p>}
                        <p>
                          {item.state}, {item.country}
                        </p>
                      </div>
                      <hr />
                      <div className={style.select_button}>
                        <button
                          type="button"
                          className="primary_btn"
                          onClick={() => {
                            setNewAddress(item);
                            setAddressBoxTitle("Edit Address");
                            setOpenAdd(true);
                          }}
                        >
                          <Edit /> Edit
                        </button>
                        <button
                          type="button"
                          className="secondary-btn"
                          onClick={() => confirmDelete(item._id)}
                        >
                          <Delete /> Delete
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
                <div
                  className={`${style.address_box} ${style.custom_address}`}
                  onClick={() => {
                    setAddressBoxTitle("Add Address");
                    setOpenAdd(true);
                  }}
                >
                  <div className={style.adress_add_button}>
                    <button type="button" className="primary_btn">
                      Add Address
                    </button>
                  </div>
                </div>
              </div>
              <OverlayBox
                open={openAdd}
                close={() => {
                  setOpenAdd(false);
                  setNewAddress({ ...defaultStructure });
                }}
                title={addressBoxTitle}
                customClass={style.customClass}
              >
                <form onSubmit={submitHandler}>
                  <div className={style.selectBox}>
                    <div>
                      <p>Full Name</p>
                      <InputText
                        placeholder="Enter name"
                        getValue={(value) => {
                          setNewAddress((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={newAddress.name}
                        customClass={style.customInputClass}
                      />
                    </div>
                    <div>
                      <p>Address Line 1</p>
                      <InputText
                        placeholder="Enter address"
                        getValue={(value) => {
                          setNewAddress((prev) => {
                            let newObject = { ...prev };
                            newObject.addressline_1 = value;
                            return newObject;
                          });
                          if (value) {
                            setErrorList((prev) => {
                              let newObject = { ...prev };
                              newObject.addressline_1 = false;
                              return newObject;
                            });
                          }
                        }}
                        required={true}
                        error={errorList.addressline_1}
                        value={newAddress.addressline_1}
                        customClass={style.customInputClass}
                      />
                    </div>
                    <div>
                      <p>Address Line 2</p>
                      <InputText
                        placeholder="Enter address"
                        getValue={(value) => {
                          setNewAddress((prev) => {
                            let newObject = { ...prev };
                            newObject.addressline_2 = value;
                            return newObject;
                          });
                          if (value) {
                            setErrorList((prev) => {
                              let newObject = { ...prev };
                              newObject.addressline_2 = false;
                              return newObject;
                            });
                          }
                        }}
                        required={true}
                        error={errorList.addressline_2}
                        value={newAddress.addressline_2}
                        customClass={style.customInputClass}
                      />
                    </div>
                    <div>
                      <p>Landmark</p>
                      <InputText
                        placeholder="Enter landmark"
                        getValue={(value) => {
                          setNewAddress((prev) => {
                            let newObject = { ...prev };
                            newObject.landmark = value;
                            return newObject;
                          });
                        }}
                        error={errorList.landmark}
                        value={newAddress.landmark}
                        customClass={style.customInputClass}
                      />
                    </div>
                    <div>
                      <p>Mobile No</p>
                      <div className={style.flex_phone}>
                        {newAddress.dial_code && (
                          <div className={style.dial_code}>
                            +{newAddress.dial_code}
                          </div>
                        )}
                        <InputText
                          type="tel"
                          placeholder="Enter mobile no"
                          maxLength={10}
                          minLength={5}
                          getValue={(value) => {
                            setNewAddress((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={newAddress.phone}
                          customClass={style.customInputClass}
                        />
                      </div>
                    </div>
                    <div>
                      <p>Country </p>
                      <SearchSelect
                        setOption={countrySelectOption}
                        placeholder={`Select Country`}
                        setSearchPlaceholder={"Search Country"}
                        getValue={(value) => {
                          console.log("value: ", value);
                          setNewAddress((prev) => {
                            let newObject = { ...prev };
                            newObject["country"] = value.value;
                            newObject["dial_code"] = value.dial_code;
                            return newObject;
                          });
                          setNewAddress((prev) => {
                            let newObject = { ...prev };
                            newObject.state = "";
                            return newObject;
                          });
                          loadStateData(value.value);
                          if (value) {
                            setErrorList((prev) => {
                              let newObject = { ...prev };
                              newObject.country = false;
                              return newObject;
                            });
                          }
                        }}
                        error={errorList.country}
                        setValue={newAddress.country}
                        customCss={`${style.custom_css_select}`}
                        customCssForBtn={style.customCssBtn}
                      />
                    </div>
                    {newAddress.country && (
                      <>
                        <div>
                          <p>Emirate </p>
                          <SearchSelect
                            setOption={stateSelectOption}
                            placeholder={`Select Emirate`}
                            getValue={(value) => {
                              if (value.value)
                                setNewAddress((prev) => {
                                  let newObject = { ...prev };
                                  newObject["state"] = value.value;
                                  return newObject;
                                });
                              if (value.value) {
                                setErrorList((prev) => {
                                  let newObject = { ...prev };
                                  newObject.state = false;
                                  return newObject;
                                });
                              }
                            }}
                            error={errorList.state}
                            loader={stateLoader}
                            setValue={newAddress.state}
                            customCss={`${style.custom_css_select}`}
                            customCssForBtn={style.customCssBtn}
                          />
                        </div>
                      </>
                    )}
                  </div>
                  <div className={style.overLayFooter}>
                    <div
                      className={`secondary-btn ${style.customBtn}`}
                      onClick={() => {
                        setOpenAdd(false);
                        setNewAddress({ ...defaultStructure });
                      }}
                    >
                      Cancel
                    </div>
                    {btnLoader ? (
                      <div
                        className={`teritary_btn ${style.customBtn}`}
                      >
                        <Loader className={style.btnLoader} />
                      </div>
                    ) : (
                      <button
                        type="submit"
                        className={`teritary_btn ${style.customBtn}`}
                      >
                        Add
                      </button>
                    )}
                  </div>
                </form>
              </OverlayBox>
            </div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
};

export default Address;
