import React, { useEffect, useRef, useState } from "react";
import style from "./address.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 { useDispatch } from "react-redux";
import { checkoutStoreActions, validateAddress } from "@/store/checkout";
import { useSelector } from "react-redux";
import Loader from "../utils/loader";
import moment from "moment";
import OverlayBox from "@/components/utils/others/overlayBox";
import { createNotification } from "@/customHook/useNotification";
import AddAddressBox from "./addAddressBox";

const AddressCheckout = (props) => {
  const [openAdd, setOpenAdd] = useState(false);
  const [btnLoader, setBtnLoader] = useState(false);
  const addressStore = useSelector((state) => state.checkoutStore.address);
  const checkoutStore = useSelector((state) => state.checkoutStore);
  const otherSellersProducts = useSelector(
    (state) => state.checkoutStore.otherSellersProducts
  );
  const deliverycharge = useSelector(
    (state) => state.checkoutStore.delivery_charge
  );
  const pickup = useSelector((state) => state.generalStore.pickup);
  const shipOrPickup = useSelector(
    (state) => state.checkoutStore.ship_or_pickup
  );
  const [deliveryOptions, setDeliveryOptions] = useState([
    { title: "Shipping", value: "shipping" },
  ]);
  const loggedIn = useSelector((state) => state.accountStore.loggedIn);
  const dispatch = useDispatch();
  const shipping = useSelector((state) => state.generalStore.shipping);
  const [loader, setLoader] = useState(true);
  const [storedAddress, setStoredAddress] = useState([]);
  const defaultStructure = {
    name: "",
    address_1: "",
    address_2: "",
    landmark: "",
    country: "",
    state: "",
    phone: "",
    zip_code: "",
    dial_code: "",
    address_id: "",
  };
  const [selected, setSelected] = useState(null);
  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 ref = useRef();

  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,
                address_1: item.addressline_1,
                address_2: item.addressline_2,
                landmark: item.landmark,
                country: item.country,
                state: item.state,
                phone: item.phone,
                dial_code: item.dial_code,
                zip_code: item.zip_code,
                address_id: item._id,
              };
            });
            console.log("newArray: ", newArray);
            return newArray;
          });
        }
        setLoader(false);
      })
      .catch((err) => {
        console.log(err);
        setLoader(false);
      });
  };

  const loadStateData = async (country) => {
    setStateLoader(true);
    setStateSelectOption([]);
    setNewAddress((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);
      });
  };

  useEffect(() => {
    loadResellerShippingData();
  }, [otherSellersProducts]);

  const loadResellerShippingData = async () => {
    console.log("otherSellersProducts: ", otherSellersProducts);
    let id = [];
    if (otherSellersProducts && otherSellersProducts.length > 0) {
      for (const item of otherSellersProducts) {
        if (item.reseller_id) {
          id.push(item.reseller_id);
        }
      }
    }
    if (id && id.length > 0) {
      setBtnLoader(true);
      await customerApi
        .get("/reseller/shipping?id=" + JSON.stringify(id), {
          cancelToken: source.token,
        })
        .then((res) => {
          console.log("gotResellerShipping, ", res.data);
          let otherSellersData = [];
          let otherSellers = {};
          let otherSellersShipping = [];
          let otherSellerPickup = [];
          if (res.data && res.data.success === true && res.data.data) {
            otherSellersShipping = res.data.data.shipping;
            otherSellerPickup = res.data.data.pickup;
          }
          if (otherSellersProducts && otherSellersProducts.length > 0) {
            for (const shipping of otherSellersShipping) {
              let delivery_charge = 0;
              let free_shipping_above = 0;
              let estimated_delivery = 0;
              let found = false;
              let dFound = false;
              otherSellers[shipping.reseller_id] = [];
              if (shipping && shipping.country && shipping.country.length > 0) {
                countryBreak: for (const item of shipping.country) {
                  if (newAddress.country == item.name) {
                    found = true;

                    delivery_charge = item.charge;
                    free_shipping_above = shipping.free_shipping_above;

                    if (item.shipping_day > 0) {
                      dFound = true;
                      estimated_delivery = moment()
                        .add(Number(item.shipping_day), "days")
                        .tz("Asia/Dubai")
                        .format("MM-DD-YYYY");
                    }
                    break countryBreak;
                  }
                }
              }
              if (shipping && shipping.state && shipping.state.length > 0) {
                stateBreak: for (const item of shipping.state) {
                  if (newAddress.state == item.name) {
                    found = true;
                    delivery_charge = item.charge;
                    free_shipping_above = shipping.free_shipping_above;

                    if (item.shipping_day > 0) {
                      dFound = true;
                      estimated_delivery = moment()
                        .add(Number(item.shipping_day), "days")
                        .tz("Asia/Dubai")
                        .format("MM-DD-YYYY");
                    }
                    break stateBreak;
                  }
                }
              }
              if (found == false && shipping && shipping.charge > 0) {
                delivery_charge = shipping.charge;
                free_shipping_above = shipping.free_shipping_above;
              }
              if (dFound == false && shipping && shipping.shipping_day > 0) {
                estimated_delivery = moment()
                  .add(Number(shipping.shipping_day), "days")
                  .tz("Asia/Dubai")
                  .format("MM-DD-YYYY");
              }
              for (const otherSellerProducts of otherSellersProducts) {
                if (otherSellerProducts.reseller_id == shipping.reseller_id) {
                  otherSellers[shipping.reseller_id].push(otherSellerProducts);
                }
              }
              let pickup = [];
              if (otherSellerPickup && otherSellerPickup.length > 0) {
                for (const item of otherSellerPickup) {
                  if (item.reseller_id == shipping.reseller_id) {
                    pickup = item.pickup;
                  }
                }
              }
              console.log("otherSellers: ", otherSellers);
              if (otherSellers && otherSellers[shipping.reseller_id])
                otherSellersData.push({
                  products: otherSellers[shipping.reseller_id],
                  shipping: {
                    delivery_charge: delivery_charge,
                    free_shipping_above: free_shipping_above,
                    estimated_delivery: estimated_delivery,
                    special_shipping: shipping.special_shipping,
                    shipping_day: shipping.shipping_day,
                    codCharge: shipping.cod_charge,
                    pickup: pickup,
                  },
                  delivery_type: {
                    type: "standard",
                    id: "",
                    reseller_id: shipping.reseller_id,
                  },
                  delivery_charge: delivery_charge,
                });
            }
            console.log("otherSellersData: ", otherSellersData);
            dispatch(
              checkoutStoreActions.storeOtherSellersCart({
                otherSellersCart: otherSellersData,
              })
            );
          }
          setBtnLoader(false);
        })
        .catch((err) => {
          console.log(err);
          setBtnLoader(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(() => {
    loadCountryData();

    console.log("addressStore.state: ", addressStore.state);
    if (addressStore.state) loadStateData(addressStore.country);
    if (addressStore.address_id) {
      for (const index in storedAddress) {
        if (storedAddress[index].address_id === addressStore.address_id) {
          console.log("hiiiii", index);
          onSetSelected(index);
        }
      }
    } else {
      setNewAddress(addressStore);
    }
    dispatch(
      checkoutStoreActions.updateCodCharge({
        cod_charge: 0,
      })
    );

    if (pickup && pickup.length > 0) {
      setDeliveryOptions((prev) => {
        let newArray = [...prev];
        newArray.push({ title: "Pick Up", value: "pickup" });
        return newArray;
      });
    }
    dispatch(
      checkoutStoreActions.updateShipOrPickup({ ship_or_pickup: "shipping" })
    );
    if (document) {
      const radiobtn = document.getElementById("shipping");
      radiobtn.checked = true;
    }
  }, []);
  useEffect(() => {
    if (loggedIn == true) {
      loadAddress();
    }
  }, [loggedIn]);
  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(() => {
    dispatch(checkoutStoreActions.storeAddress({ address: newAddress }));
  }, [newAddress]);

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

  const submitHandler = () => {
    let errorFound = false;
    if (shipOrPickup === "shipping")
      for (const item in addressStore) {
        if (
          item == "zip_code" ||
          item == "landmark" ||
          item == "address_id" ||
          item == "delivery_charge"
        )
          continue;
        if (!addressStore[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) {
      props.onAddressSubmit();
    }
  };

  const onSetSelected = (index) => {
    console.log("hi", index);
    setSelected(index);
    setNewAddress(storedAddress[index]);
  };

  useEffect(() => {
    console.log("selected:", selected);
    if (selected === null) {
      ref.current && ref.current.scrollIntoView();
    }
  }, [selected]);

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

  return (
    <div className={style.section_data}>
      <div className={style.delivery_type}>
        <p>Delivery Type</p>
        {deliveryOptions.map((item, index) => (
          <label for={item.value} key={index}>
            <input
              type="radio"
              onClick={(e) => {
                console.log("e:", e);
                dispatch(
                  checkoutStoreActions.updateShipOrPickup({
                    ship_or_pickup: e.target.value,
                  })
                );
              }}
              name="delivery_type"
              value={item.value}
              id={item.value}
            />{" "}
            {item.title}
          </label>
        ))}
      </div>
      {shipOrPickup === "shipping" && (
        <>
          <p>Shipping Address</p>
          {loader && <Loader className={style.loader} />}
          {!loader && (
            <>
              <div className={style.stored_shipping_address}>
                <div className={style.selectBox}>
                  {storedAddress.map((item, index) => (
                    <div
                      className={`${style.address_box} ${
                        selected == index && style.selected
                      } `}
                      key={item.name}
                      onClick={() => {
                        if (selected === index) {
                          setSelected(null);
                          setNewAddress(defaultStructure);
                        } else {
                          onSetSelected(index);
                        }
                      }}
                    >
                      <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.address_1}</p>
                        <p>{item.address_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}>
                        {selected == index ? (
                          <button
                            type="button"
                            className="primary_btn_no_animation upperCase"
                          >
                            Selected Address
                          </button>
                        ) : (
                          <button type="button" className="primary_btn">
                            Deliver To This Address
                          </button>
                        )}
                      </div>
                    </div>
                  ))}

                  <div
                    className={`${style.address_box} ${style.custom_address}`}
                    onClick={() => setOpenAdd(true)}
                  >
                    <div className={style.adress_add_button}>
                      <button type="button" className="primary_btn">
                        Add Address
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              {/* Add Overlay Box */}
              <AddAddressBox
                loadAddress={() => loadAddress()}
                open={openAdd}
                close={() => {
                  setOpenAdd(false);
                }}
              />
              <form onSubmit={submitHandler}>
                {(selected === null || storedAddress.length == 0) && (
                  <>
                    <p className={style.seperator_text}>OR</p>
                    <div className={style.selectBox}>
                      <div ref={ref}>
                        <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={addressStore.name}
                          customClass={style.customInputClass}
                        />
                      </div>
                      <div>
                        <p>Address Line 1</p>
                        <InputText
                          placeholder="Enter address"
                          getValue={(value) => {
                            setNewAddress((prev) => {
                              let newObject = { ...prev };
                              newObject.address_1 = value;
                              return newObject;
                            });
                            if (value) {
                              setErrorList((prev) => {
                                let newObject = { ...prev };
                                newObject.address_1 = false;
                                return newObject;
                              });
                            }
                          }}
                          required={true}
                          error={errorList.address_1}
                          value={addressStore.address_1}
                          customClass={style.customInputClass}
                        />
                      </div>
                      <div>
                        <p>Address Line 2</p>
                        <InputText
                          placeholder="Enter address"
                          getValue={(value) => {
                            setNewAddress((prev) => {
                              let newObject = { ...prev };
                              newObject.address_2 = value;
                              return newObject;
                            });
                            if (value) {
                              setErrorList((prev) => {
                                let newObject = { ...prev };
                                newObject.address_2 = false;
                                return newObject;
                              });
                            }
                          }}
                          required={true}
                          error={errorList.address_2}
                          value={addressStore.address_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={addressStore.landmark}
                          customClass={style.customInputClass}
                        />
                      </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={addressStore.country}
                          customCss={`${style.custom_css_select}`}
                          customCssForBtn={style.customCssBtn}
                        />
                      </div>
                      {addressStore.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={addressStore.state}
                              customCss={`${style.custom_css_select}`}
                              customCssForBtn={style.customCssBtn}
                            />
                          </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={addressStore.phone}
                            customClass={style.customInputClass}
                          />
                        </div>
                      </div>
                    </div>
                  </>
                )}
                <div className={style.option_button}>
                  {/* <button
            type="button"
            className={`secondary-btn ${style.secondary_btn}`}
          >
            Back
          </button> */}
                  <div></div>
                </div>
              </form>
            </>
          )}
        </>
      )}
      {btnLoader ? (
        <button type="button" className={`primary_btn ${style.primary_btn}`}>
          <Loader className={style.btnLoader} />
        </button>
      ) : (
        <button
          type="button"
          onClick={() => submitHandler()}
          className={`primary_btn ${style.primary_btn}`}
        >
          Proceed
        </button>
      )}
      <div className={style.button_layer_footer}></div>
    </div>
  );
};

export default AddressCheckout;
