import React, { useEffect, useState } from "react";
import style from "./review.module.css";
import Image from "next/image";
import { Payment } from "@mui/icons-material";
import {
  getTotalStats,
  getCheckoutCart,
  getPaymentInput,
} from "@/store/checkout";
import { useDispatch, useSelector } from "react-redux";
import Loader from "@/components/utils/loader";
import { customerApi } from "@/api/api";
import { useRouter } from "next/router";
import InputText from "../utils/inputText";
import { createNotification } from "../../customHook/useNotification";
import NextImage from "@/other/NextImage";
import { checkoutStoreActions } from "@/store/checkout";
import HtmlParser from "react-html-parser";
import { loadCart, loadWishlist } from "@/store/index";
import moment from "moment";
import { loadSetting } from "@/store/index";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import "react-datepicker/dist/react-datepicker-cssmodules.css";
import { useFullPhoneValidation } from "@/customHook/useValidation";

const ReviewCheckout = (props) => {
  const totalStats = useSelector(getTotalStats);
  const checkoutCart = useSelector(getCheckoutCart);
  const delivery_type = useSelector(
    (state) => state.checkoutStore.delivery_type
  );
  const contactPhone = useSelector(
    (state) => state.checkoutStore.contact_phone
  );
  const selectedPickup = useSelector((state) => state.checkoutStore.pickup);
  const pickupDate = useSelector((state) => state.checkoutStore.pickup_date);
  const address = useSelector((state) => state.checkoutStore.address);
  const standard_shipping_day = useSelector(
    (state) => state.checkoutStore.standard_shipping_day
  );
  const paymentInput = useSelector(getPaymentInput);
  const dispatch = useDispatch();
  const defaultPaymentAccepted = useSelector(
    (state) => state.generalStore.default_accepted_payment
  );
  const shipOrPickup = useSelector(
    (state) => state.checkoutStore.ship_or_pickup
  );
  const shipping = useSelector((state) => state.generalStore.shipping);
  const currencyType = useSelector((state) => state.generalStore.currency_type);
  const [loader, setLoader] = useState(false);
  const router = useRouter();
  const [paymentOptions, setPaymentOptions] = useState();
  const [errorList, setErrorList] = useState({ paymentMethod: false });
  const [discountMessage, setDiscountMessage] = useState("");
  const [validation, setValidation] = useState(false);
  const [error, setError] = useState("");
  const [errorContact, setErrorContact] = useState(false);

  const contactValidation = useFullPhoneValidation(contactPhone);

  const loadDiscountMessage = async (ctx) => {
    await Promise.all([
      customerApi.get("/site/contents?group_code=discount_section"),
    ]).then((res) => {
      console.log("res.data, ", res[0].data);
      let newArray = { ...res[0].data.result };
      setDiscountMessage(newArray);
    });
  };

  const [paymentMethod, setPaymentMethod] = useState();

  useEffect(() => {
    loadDiscountMessage();
    loadSetting();
  }, []);

  useEffect(() => {
    setError("");
    setErrorContact(false);
    let rError = false;
    if (
      !["bank", "card(stripe)", "card(paytabs)", "cash_on_delivery"].includes(
        paymentMethod
      ) ||
      (paymentMethod === "bank" && !bank_owner_details.iban_no)
    ) {
      setError("Select Payment Method");
      rError = true;
    }

    if (!rError && shipOrPickup === "pickup") {
      for (const item of checkoutCart) {
        if (!item.reseller_id) {
          if (
            !selectedPickup.name ||
            !selectedPickup.address ||
            !selectedPickup.phone
          ) {
            setError("Select Pickup Location");
            rError = true;
            break;
          }
        } else {
          if (
            !item.selected_pickup ||
            !item.selected_pickup.name ||
            !item.selected_pickup.address ||
            !item.selected_pickup.phone
          ) {
            setError("Select Pickup Location");
            rError = true;
            break;
          }
        }
      }
    }
    if (!rError && !pickupDate && shipOrPickup === "pickup") {
      setError("Select Pickup Date");
      rError = true;
    }

    if (!contactValidation.value) {
      setErrorContact(true);
    }

    if (!rError && !contactValidation.value) {
      setError("Wrong Contact Number Format");
      rError = true;
    }

    if (!rError) {
      setValidation(true);
    } else {
      setValidation(false);
    }
  }, [checkoutCart, selectedPickup, paymentMethod, pickupDate, contactPhone]);

  const [bankDetails, setBankDetails] = useState({
    iban_no: "",
    account_no: "",
    account_name: "",
    bank_name: "",
    reference_no: "",
  });

  const [errorListBank, setErrorListBank] = useState({
    iban_no: false,
    account_no: false,
    account_name: false,
    bank_name: false,
    reference_no: false,
  });

  const onPendingPaymentMethodSubmit = async () => {
    if (!paymentMethod) {
      setErrorList({ paymentMethod: true });
      createNotification("error", "Complete Required Field");
      return;
    } else {
      setErrorList({ paymentMethod: false });
    }
    if (paymentMethod === "bank") {
      let errorFound = false;
      for (const item in bankDetails) {
        if (!bankDetails[item]) {
          setErrorListBank((prev) => {
            let newObject = { ...prev };
            newObject[item] = true;
            return newObject;
          });
          errorFound = true;
        } else {
          setErrorListBank((prev) => {
            let newObject = { ...prev };
            newObject[item] = false;
            return newObject;
          });
        }
      }
      if (errorFound === true) {
        createNotification("error", "Complete Required Field");
        return;
      }
    } else {
      setBankDetails();
    }
    setLoader(true);
    await customerApi
      .post("/order/place/other", {
        ...paymentInput,
        type: "cart",
        payment_method: paymentMethod,
        bank_details: bankDetails,
      })
      .then((res) => {
        if (res.data.success === true) {
          createNotification("success", "Successfully Placed Order");
          dispatch(checkoutStoreActions.clearDiscount());
          dispatch(checkoutStoreActions.clearPickup());
          loadCart();
          loadWishlist();
          router.push("/order/success");
        } else {
          dispatch(checkoutStoreActions.clearDiscount());
          dispatch(checkoutStoreActions.clearPickup());
          router.push("/order/failed");
        }
        setLoader(false);
      })
      .catch((err) => {
        console.log(err);
        setLoader(false);
        createNotification("error", "Something Went Wrong");
        dispatch(checkoutStoreActions.clearDiscount());
        dispatch(checkoutStoreActions.clearPickup());
        router.push("/order/failed");
      });
    setLoader(false);
  };

  // Discount function

  const [discount, setDiscount] = useState();
  const [appliedDiscount, setAppliedDiscount] = useState({
    code: "",
    percentage: "",
  });
  const [discountLoader, setDiscountLoader] = useState(false);
  const [discountErr, setDiscountErr] = useState();
  const discountCheck = async () => {
    setDiscountLoader(true);
    setDiscountErr();
    console.log("discount code:", discount);
    await customerApi
      .get("/discount?discount_code=" + discount)
      .then(async (res) => {
        console.log("Res:", res);
        if (res.data.success === true) {
          if (res.data.data.type === "first_time_payment") {
            const orderCount = await customerApi.get("/orders/count");
            console.log("orderCount: ", orderCount);
            if (orderCount.data.count == 0) {
              setAppliedDiscount({
                code: res.data.data.code,
                percentage: res.data.data.percentage,
              });
              dispatch(
                checkoutStoreActions.updateDiscount({
                  discount: {
                    code: res.data.data.code,
                    percentage: res.data.data.percentage,
                    category: res.data.data.categories,
                  },
                })
              );
            } else {
              setDiscountErr("Not first time purchase");
            }
          } else if (res.data.data.type === "one_time") {
            const params = JSON.stringify({ code: res.data.data.code });
            const orderCount = await customerApi.get(
              "/orders/count?params=" + params
            );
            console.log("orderCount: ", orderCount);
            if (orderCount.data.count == 0) {
              setAppliedDiscount({
                code: res.data.data.code,
                percentage: res.data.data.percentage,
              });
              dispatch(
                checkoutStoreActions.updateDiscount({
                  discount: {
                    code: res.data.data.code,
                    percentage: res.data.data.percentage,
                    category: res.data.data.categories,
                  },
                })
              );
            } else {
              setDiscountErr("Code is already used");
            }
          } else if (res.data.data.type === "all") {
            setAppliedDiscount({
              code: res.data.data.code,
              percentage: res.data.data.percentage,
            });
            dispatch(
              checkoutStoreActions.updateDiscount({
                discount: {
                  code: res.data.data.code,
                  percentage: res.data.data.percentage,
                  category: res.data.data.categories,
                },
              })
            );
          }
        } else {
          setDiscountErr("Invalid Discount Code");
        }
        setDiscountLoader(false);
      })
      .catch((err) => {
        console.log(err);
        setDiscountLoader(false);
        setDiscountErr("Failed to apply discount");
      });
  };

  //

  const onSubmitClick = async (type) => {
    setLoader(true);
    let paymentUrl;
    if (type === "stripe") {
      paymentUrl = await customerApi
        .post("/payment/stripe/checkout", { ...paymentInput, type: "cart" })
        .then((res) => {
          if (res.data.url) {
            window.location.href = res.data.url;
          }
          setLoader(false);
        })
        .catch((err) => {
          console.log(err);
          setLoader(false);
        });
    } else if (type === "paytabs") {
      await customerApi
        .post("/payment/paytabs/checkout", { ...paymentInput, type: "cart" })
        .then((res) => {
          if (res.data.url) {
            window.location.href = res.data.url;
          }
          setLoader(false);
        })
        .catch((err) => {
          console.log(err);
          setLoader(false);
        });
    }
  };
  const onPlaceOrder = async () => {
    setLoader(true);
    const paymentUrl = await customerApi
      .post("/order/request", { ...paymentInput, type: "cart" })
      .then((res) => {
        if (res.data.success === true) {
          dispatch(checkoutStoreActions.clearDiscount());
          dispatch(checkoutStoreActions.clearPickup());
          router.push("/order/success");
        } else {
          router.push("/order/failed");
          dispatch(checkoutStoreActions.clearDiscount());
          dispatch(checkoutStoreActions.clearPickup());
        }
        setLoader(false);
      })
      .catch((err) => {
        console.log(err);
        dispatch(checkoutStoreActions.clearDiscount());
        dispatch(checkoutStoreActions.clearPickup());
        loadCart();
        loadWishlist();
        router.push("/order/failed");
        setLoader(false);
      });
  };
  const onBackClicked = () => {
    props.onBackClicked("address");
  };
  useEffect(() => {
    if (defaultPaymentAccepted && defaultPaymentAccepted.length > 0) {
      let options = [];
      for (const item of defaultPaymentAccepted) {
        options.push({ title: item.replaceAll("_", " "), value: item });
      }
      setPaymentOptions(options);
    }
  }, [defaultPaymentAccepted]);
  useEffect(() => {
    console.log("checkoutCart: ", checkoutCart);
    let filterPayment = defaultPaymentAccepted;
    if (
      checkoutCart &&
      checkoutCart[0] &&
      checkoutCart[0].payment_accepted &&
      checkoutCart[0].payment_accepted.length > 0
    ) {
      filterPayment = checkoutCart[0].payment_accepted;
    }
    for (const item of checkoutCart) {
      if (item.payment_accepted && item.payment_accepted.length > 0) {
        filterPayment = filterPayment.filter((value) =>
          item.payment_accepted.includes(value)
        );
      }
    }
    console.log("filterPayment: ", filterPayment);
    if (filterPayment.length > 0) {
      let options = [];
      for (const item of filterPayment) {
        options.push({ title: item.replaceAll("_", " "), value: item });
      }
      setPaymentOptions(options);
    }
  }, [checkoutCart]);
  useEffect(() => {
    console.log("paymentInput: ", paymentInput);
    if (shipOrPickup === "pickup") {
      dispatch(checkoutStoreActions.cleactContactPhone());
    } else if (shipOrPickup === "shipping") {
      dispatch(
        checkoutStoreActions.updateContactPhone({
          contact_phone: "+" + address.dial_code + "" + address.phone,
        })
      );
    }
  }, []);

  const getPrice = (prices, price_type, quantity) => {
    let price = 0;
    if (price_type === "quantity_wise") {
      for (const item of prices) {
        if (quantity <= item.quantity) {
          price = Number(item.price);
          break;
        }
      }
    } else {
      price = Number(prices);
    }
    return price.toFixed(2);
  };

  // Bank Details Functions

  const [bank_owner_details, setBankOwnerDetails] = useState({
    iban_no: "",
    account_no: "",
    account_name: "",
    bank_name: "",
  });
  const [bankLoader, setBankLoader] = useState(false);

  useEffect(() => {
    if (paymentOptions && paymentOptions.length > 0)
      for (const item of paymentOptions) {
        if (item.value === "bank") {
          loadBank();
        }
      }
  }, [paymentOptions]);

  const loadBank = async () => {
    setBankLoader(true);
    await customerApi
      .get("/general")
      .then((res) => {
        if (res.data.success === true) {
          setBankOwnerDetails(res.data.data.bank_details);
        }
        setBankLoader(false);
      })
      .catch((err) => {
        console.log("Err:", err);
        setBankLoader(false);
      });
  };

  useEffect(() => {
    return () => {
      dispatch(checkoutStoreActions.clearDiscount());
      dispatch(checkoutStoreActions.clearPickup());
    };
  }, []);

  // Shipping Estimated Charge

  useEffect(() => {
    calculateStandardCharge();
  }, [address]);

  const calculateStandardCharge = () => {
    let found = false;
    let dFound = false;
    console.log("shipping: ", shipping);
    if (shipping && shipping.country && shipping.country.length > 0) {
      for (const item of shipping.country) {
        if (address.country == item.name) {
          found = true;
          dispatch(
            checkoutStoreActions.updateDeliveryCharge({
              delivery_charge: item.charge,
            })
          );
          dispatch(
            checkoutStoreActions.updateFreeShippingAbove({
              free_shipping_above: shipping.free_shipping_above,
            })
          );
          if (item.shipping_day > 0) {
            dFound = true;
            dispatch(
              checkoutStoreActions.updateStandardEstimatedDelivery({
                estimated_delivery: moment()
                  .add(Number(item.shipping_day), "days")
                  .tz("Asia/Dubai")
                  .format("ll"),
                standard_shipping_day: item.shipping_day,
              })
            );
          }
          break;
        }
      }
    }
    if (shipping && shipping.state && shipping.state.length > 0) {
      for (const item of shipping.state) {
        if (address.state == item.name) {
          found = true;
          dispatch(
            checkoutStoreActions.updateDeliveryCharge({
              delivery_charge: item.charge,
            })
          );
          dispatch(
            checkoutStoreActions.updateFreeShippingAbove({
              free_shipping_above: shipping.free_shipping_above,
            })
          );
          if (item.shipping_day > 0) {
            dFound = true;
            dispatch(
              checkoutStoreActions.updateStandardEstimatedDelivery({
                estimated_delivery: moment()
                  .add(Number(item.shipping_day), "days")
                  .tz("Asia/Dubai")
                  .format("ll"),
                standard_shipping_day: item.shipping_day,
              })
            );
          }
          break;
        }
      }
    }
    if (found == false && shipping && shipping.charge > 0) {
      dispatch(
        checkoutStoreActions.updateDeliveryCharge({
          delivery_charge: shipping.charge,
        })
      );
      dispatch(
        checkoutStoreActions.updateFreeShippingAbove({
          free_shipping_above: shipping.free_shipping_above,
        })
      );
    }
    if (dFound == false && shipping && shipping.shipping_day > 0) {
      console.log("shipping: ", shipping);
      dispatch(
        checkoutStoreActions.updateStandardEstimatedDelivery({
          estimated_delivery: moment()
            .add(Number(shipping.shipping_day), "days")
            .tz("Asia/Dubai")
            .format("ll"),
          standard_shipping_day: shipping.shipping_day,
        })
      );
    }
  };
  return (
    <div className={style.section_data}>
      <p>Review</p>
      <div className={style.review_form}>
        {checkoutCart &&
          checkoutCart.length > 0 &&
          checkoutCart.map((item, index) => (
            <div className={`${style.box_design}`} key={index}>
              {item.products.map((innerItem, index) => (
                <div
                  className={`${style.product_section}`}
                  key={`${innerItem.name}_${index}`}
                >
                  <div className={style.product_data}>
                    <div className={style.product_image}>
                      <NextImage
                        src={innerItem.image && innerItem.image}
                        alt="image"
                        fill
                      />
                    </div>

                    <div className={style.selectBox}>
                      <div>
                        Name:{" "}
                        <span className="capitalize">
                          {innerItem.name
                            .replaceAll("<b>", "")
                            .replaceAll("</b>", "")
                            .replaceAll("<i>", "")
                            .replaceAll("</i>", "")
                            .replaceAll("</br>", "")}
                        </span>
                      </div>
                      {/* {totalStats.estimatedDelivery && (
                    <div>
                      Estimated Delivery:
                      <span>{totalStats.estimatedDelivery}</span>
                    </div>
                  )} */}
                    </div>
                  </div>

                  {getPrice(
                    innerItem.price,
                    innerItem.price_type,
                    innerItem.qty
                  ) > 0 && (
                    <div className={style.product_price}>
                      <div className={style.purchase_detail}>
                        <div
                          className={`${style.purchase_data} ${style.color_dark}`}
                        >
                          <div className={`${style.purchase_title}`}>
                            Qnty :
                          </div>
                          <div
                            className={`${style.purchase_value} ${style.title_dark}`}
                          >
                            {innerItem.qty} x{" "}
                            {getPrice(
                              innerItem.price,
                              innerItem.price_type,
                              innerItem.qty
                            )}{" "}
                            {currencyType}
                          </div>
                        </div>

                        {innerItem.tax && innerItem.tax > 0 ? (
                          <div
                            className={`${style.purchase_data} ${style.color_dark}`}
                          >
                            <div className={style.purchase_title}>Tax :</div>
                            <div
                              className={`${style.purchase_value} ${style.title_dark}`}
                            >
                              <div className={style.grand_total}>
                                {innerItem.tax}%
                              </div>
                            </div>
                          </div>
                        ) : (
                          ""
                        )}
                        <div
                          className={`${style.purchase_data} ${style.color_dark}`}
                        >
                          <div className={style.purchase_title}>Price :</div>
                          <div
                            className={`${style.purchase_value} ${style.title_dark}`}
                          >
                            {innerItem.offer ? (
                              <div className={style.total_price}>
                                {innerItem.total_price} {currencyType}
                              </div>
                            ) : (
                              ""
                            )}
                            <div className={style.grand_total}>
                              {innerItem.total_before_tax} {currencyType}
                            </div>
                          </div>
                        </div>
                        {/* Discount Section */}
                        {innerItem.discount_percentage &&
                          innerItem.discount_percentage > 0 && (
                            <div
                              className={`${style.purchase_data} ${style.color_dark}`}
                            >
                              <div className={style.purchase_title}>
                                Discount :
                              </div>
                              <div className={`${style.purchase_value}`}>
                                {innerItem.discount_percentage ? (
                                  <div className={style.discount_percentage}>
                                    {innerItem.discount_percentage}%
                                  </div>
                                ) : (
                                  ""
                                )}
                              </div>
                            </div>
                          )}
                        {/*  */}
                        <div
                          className={`${style.purchase_data} ${style.color_dark}`}
                        >
                          <div className={style.purchase_title}>Total :</div>
                          <div
                            className={`${style.purchase_value} ${style.title_dark}`}
                          >
                            <div className={style.grand_total}>
                              {innerItem.grand_total} {currencyType}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              ))}
              {/* Shipping Selection */}
              {totalStats.totalPrice > 0 && shipOrPickup === "shipping" ? (
                <div className={`${style.shipping_type_section} mt-3`}>
                  <p>Select Shipping</p>
                  <div className={style.shipping_selection}>
                    {item && item.shipping && item.shipping.shipping_day && (
                      <div
                        className={`${style.shipping_btn} ${
                          item.delivery_type && item.delivery_type.reseller_id
                            ? item.delivery_type.type == "standard"
                              ? style.active
                              : ""
                            : delivery_type.type === "standard"
                            ? style.active
                            : ""
                        }`}
                        onClick={() => {
                          if (
                            item.delivery_type &&
                            item.delivery_type.reseller_id
                          ) {
                            console.log(
                              "resellerhi",
                              item.delivery_type.reseller_id
                            );
                            dispatch(
                              checkoutStoreActions.updateDeliveryForOtherSellers(
                                {
                                  reseller_id: item.delivery_type.reseller_id,
                                  delivery_type: {
                                    type: "standard",
                                    id: "",
                                    reseller_id: item.delivery_type.reseller_id,
                                  },
                                  delivery_charge:
                                    item.shipping.delivery_charge,
                                }
                              )
                            );
                          } else {
                            dispatch(
                              checkoutStoreActions.updateSelectedDeliveryType({
                                delivery_type: {
                                  type: "standard",
                                  id: "",
                                },
                              })
                            );
                            calculateStandardCharge();
                          }
                        }}
                      >
                        Standard Delivery
                        <br />
                        <span>
                          Delivery in {item.shipping.shipping_day} days
                        </span>
                      </div>
                    )}
                    {item &&
                      item.shipping &&
                      item.shipping.special_shipping &&
                      item.shipping.special_shipping.length > 0 &&
                      item.shipping.special_shipping.map(
                        (shippingItem, sindex) =>
                          (shippingItem.country.includes(address.country) ||
                            shippingItem.state.includes(address.state)) &&
                          (!shippingItem.before_time ||
                            moment()
                              .tz("Asia/Dubai")
                              .diff(
                                moment(shippingItem.before_time, "HH:mm")
                              ) <= 0) && (
                            <div
                              className={`${style.shipping_btn} ${
                                item.delivery_type.reseller_id
                                  ? item.delivery_type.id == shippingItem._id &&
                                    item.delivery_type.type != "standard"
                                    ? style.active
                                    : ""
                                  : delivery_type.id == shippingItem._id &&
                                    delivery_type.type != "standard"
                                  ? style.active
                                  : ""
                              }`}
                              onClick={() => {
                                if (item.delivery_type.reseller_id) {
                                  console.log("resellerhi", item.delivery_type);
                                  dispatch(
                                    checkoutStoreActions.updateDeliveryForOtherSellers(
                                      {
                                        reseller_id:
                                          item.delivery_type.reseller_id,
                                        delivery_type: {
                                          type: "special",
                                          id: shippingItem._id,
                                          reseller_id:
                                            item.delivery_type.reseller_id,
                                        },
                                        delivery_charge: shippingItem.charge,
                                      }
                                    )
                                  );
                                } else {
                                  dispatch(
                                    checkoutStoreActions.updateSelectedDeliveryType(
                                      {
                                        delivery_type: {
                                          type: "special",
                                          id: shippingItem._id,
                                        },
                                      }
                                    )
                                  );
                                  dispatch(
                                    checkoutStoreActions.updateDeliveryCharge({
                                      delivery_charge: shippingItem.charge,
                                    })
                                  );
                                }
                              }}
                              key={`${sindex}_${shippingItem._id}`}
                            >
                              {shippingItem.name}{" "}
                              {shippingItem.before_time && (
                                <div className={style.time_within}>
                                  (Order with
                                  {moment(
                                    shippingItem.before_time,
                                    "HH:mm"
                                  ).fromNow()}
                                  )
                                </div>
                              )}
                              <br />
                              <span>
                                Delivery by{" "}
                                {
                                  moment()
                                    .add(
                                      Number(shippingItem.shipping_day),
                                      "days"
                                    )
                                    .tz("Asia/Dubai")
                                    .calendar()
                                    .split(" at")[0]
                                }
                              </span>
                            </div>
                          )
                      )}
                  </div>
                </div>
              ) : (
                <div className={`${style.shipping_type_section} mt-3`}>
                  <p>Select Pickup Location</p>
                  <div className={style.pickup_selection}>
                    {item &&
                      item.pickup &&
                      item.pickup.length > 0 &&
                      item.pickup.map((pickupItem, pindex) => (
                        <div
                          className={`${style.shipping_btn} ${
                            item.delivery_type && item.delivery_type.reseller_id
                              ? item.delivery_type.id == pickupItem.name
                                ? style.active
                                : ""
                              : selectedPickup.name == pickupItem.name &&
                                selectedPickup.phone == pickupItem.phone &&
                                selectedPickup.address == pickupItem.address
                              ? style.active
                              : ""
                          }`}
                          onClick={() => {
                            if (
                              item.delivery_type &&
                              item.delivery_type.reseller_id
                            ) {
                              console.log("resellerhi", item.delivery_type);
                              dispatch(
                                checkoutStoreActions.updatePickupForOtherSellers(
                                  {
                                    reseller_id: item.delivery_type.reseller_id,
                                    pickup: {
                                      name: pickupItem.name,
                                      address: pickupItem.address,
                                      phone: pickupItem.phone,
                                    },
                                  }
                                )
                              );
                            } else {
                              dispatch(
                                checkoutStoreActions.updateSelectedPickup({
                                  pickup: {
                                    name: pickupItem.name,
                                    address: pickupItem.address,
                                    phone: pickupItem.phone,
                                  },
                                })
                              );
                            }
                          }}
                          key={`${pindex}_${pickupItem._id}`}
                        >
                          {pickupItem.name && (
                            <div className={style.pickupName}>
                              {pickupItem.name}
                            </div>
                          )}
                          <br />
                          <span>{pickupItem.address}</span>
                          <br />
                          <span>{pickupItem.phone}</span>
                        </div>
                      ))}
                  </div>
                </div>
              )}
              {paymentMethod === "cash_on_delivery" && (
                <div className={style.codChargeClass}>
                  {item.reseller_id
                    ? item.shipping.codCharge
                      ? `COD Charge: ${item.shipping.codCharge} ${currencyType}`
                      : ``
                    : item.shipping.cod_charge
                    ? `COD Charge: ${item.shipping.cod_charge} ${currencyType}`
                    : ``}
                </div>
              )}
              {/* Shipping Selection End */}
            </div>
          ))}

        {shipOrPickup === "shipping" && (
          <div className={`${style.delivery_address} ${style.box_design}`}>
            <p>Shipping Address</p>
            <div className={style.address}>
              <p className={style.stored_name}>{address.name}</p>
              <div className={style.stored_address}>
                <p>
                  {address.dial_code && `+${address.dial_code}`}
                  {address.phone.replace(/^0+/, "")}
                </p>
                <p>{address.address_1}</p>
                <p>{address.address_2}</p>
                {address.landmark && <p>{address.landmark}</p>}
                {address.zip_code && <p>{address.zip_code}</p>}
                <p>
                  {address.state}, {address.country}
                </p>
              </div>
            </div>
          </div>
        )}

        {totalStats.totalPrice > 0 && shipOrPickup === "pickup" && (
          <div className={`${style.discount_section} ${style.box_design}`}>
            <p>Pickup Date</p>
            <div className={style.pickup_date_input}>
              <DatePicker
                className={style.datepicker}
                showIcon
                minDate={moment().add(1, "days").format("YYYY-MM-DD")}
                placeholderText="dd/mm/yyyy"
                onChange={(value) => {
                  dispatch(
                    checkoutStoreActions.updatePickupDate({
                      pickup_date: value,
                    })
                  );
                }}
                selected={pickupDate}
                onKeyDown={(e) => {
                  e.preventDefault();
                }}
              />
            </div>
          </div>
        )}

        {
          <div className={`${style.discount_section} ${style.box_design}`}>
            <p>Contact Number</p>
            <div className={style.phone_input}>
              <InputText
                type="tel"
                placeholder="Enter contact number"
                maxLength={13}
                minLength={10}
                getValue={(value) => {
                  dispatch(
                    checkoutStoreActions.updateContactPhone({
                      contact_phone: value,
                    })
                  );
                }}
                required={true}
                error={errorContact}
                value={contactPhone}
                customCss={style.phoneInput}
              />
            </div>
            {discountMessage &&
              discountMessage.discount_message &&
              discountMessage.discount_message.content &&
              discountMessage.discount_message.content.length > 0 && (
                <div className={`${style.discount_message}`}>
                  {HtmlParser(discountMessage.discount_message.content[0])}
                </div>
              )}
            {discountErr && (
              <div className={`${style.discount_code_err}`}>{discountErr}</div>
            )}
          </div>
        }

        {totalStats.totalPrice > 0 &&
          paymentOptions &&
          paymentOptions.length > 0 && (
            <div
              className={`${style.delivery_address} ${style.box_design} ${
                errorList.paymentMethod ? style.error : ""
              }`}
            >
              <p>Payment Method</p>
              <div className={style.payment_section}>
                {paymentOptions.map((item) => (
                  <div className={style.payment_section_radio} key={item.value}>
                    <input
                      type="radio"
                      name="paymentSelected"
                      value={item.value}
                      id={item.value}
                      onClick={() => {
                        setPaymentMethod(item.value);
                        if (item.value === "cash_on_delivery") {
                          if (shipping)
                            dispatch(
                              checkoutStoreActions.updateCodCharge({
                                cod_charge: shipping.cod_charge,
                              })
                            );
                        } else {
                          dispatch(
                            checkoutStoreActions.updateCodCharge({
                              cod_charge: 0,
                            })
                          );
                        }
                      }}
                    />
                    <label htmlFor={item.value} className="capitalize">
                      {item.title}
                    </label>
                  </div>
                ))}
              </div>
              {paymentMethod === "cash_on_delivery" &&
                shipping &&
                shipping.cod_charge &&
                shipping.cod_charge > 0 && (
                  <p className={style.cod_message}>
                    Total COD Charge :{" "}
                    <span>
                      {totalStats.cod_charge} {currencyType}
                    </span>
                  </p>
                )}
              {paymentMethod === "bank" &&
                (bank_owner_details && bank_owner_details.iban_no ? (
                  <>
                    {!bankLoader &&
                      bank_owner_details &&
                      bank_owner_details.iban_no &&
                      bank_owner_details.account_no &&
                      bank_owner_details.account_name &&
                      bank_owner_details.bank_name && (
                        <>
                          <div className={style.bank_details}>
                            <h6>Bank Details</h6>
                            <p>
                              <b>IBAN No : </b> {bank_owner_details.iban_no}
                            </p>
                            <p>
                              <b>Account Name : </b>{" "}
                              {bank_owner_details.account_name}
                            </p>
                            <p>
                              <b>Account No : </b>{" "}
                              {bank_owner_details.account_no}
                            </p>
                            <p>
                              <b>Bank Name : </b> {bank_owner_details.bank_name}
                            </p>
                          </div>
                        </>
                      )}
                    {bankLoader && (
                      <div className={style.bank_details}>
                        <Loader className={style.loader} />
                      </div>
                    )}
                    <div className={style.section_data_payment}>
                      <div>
                        <p>IBAN No</p>
                        <InputText
                          type="text"
                          placeholder="Enter IBAN No"
                          getValue={(value) => {
                            setBankDetails((prev) => {
                              let newObject = { ...prev };
                              newObject.iban_no = value;
                              return newObject;
                            });
                            if (value) {
                              setErrorListBank((prev) => {
                                let newObject = { ...prev };
                                newObject.iban_no = false;
                                return newObject;
                              });
                            }
                          }}
                          required={true}
                          error={errorListBank.iban_no}
                          value={bankDetails.iban_no}
                          customClass={style.customInputClass}
                        />
                      </div>
                      <div>
                        <p>Account Name</p>
                        <InputText
                          placeholder="Enter Account Name"
                          getValue={(value) => {
                            setBankDetails((prev) => {
                              let newObject = { ...prev };
                              newObject.account_name = value;
                              return newObject;
                            });
                            if (value) {
                              setErrorListBank((prev) => {
                                let newObject = { ...prev };
                                newObject.account_name = false;
                                return newObject;
                              });
                            }
                          }}
                          required={true}
                          error={errorListBank.account_name}
                          value={bankDetails.account_name}
                          customClass={style.customInputClass}
                        />
                      </div>
                      <div>
                        <p>Account Number</p>
                        <InputText
                          type="number"
                          placeholder="Enter Account Number"
                          getValue={(value) => {
                            setBankDetails((prev) => {
                              let newObject = { ...prev };
                              newObject.account_no = value;
                              return newObject;
                            });
                            if (value) {
                              setErrorListBank((prev) => {
                                let newObject = { ...prev };
                                newObject.account_no = false;
                                return newObject;
                              });
                            }
                          }}
                          required={true}
                          error={errorListBank.account_no}
                          value={bankDetails.account_no}
                          customClass={style.customInputClass}
                        />
                      </div>
                      <div>
                        <p>Bank Name</p>
                        <InputText
                          placeholder="Enter Bank Name"
                          getValue={(value) => {
                            setBankDetails((prev) => {
                              let newObject = { ...prev };
                              newObject.bank_name = value;
                              return newObject;
                            });
                            if (value) {
                              setErrorListBank((prev) => {
                                let newObject = { ...prev };
                                newObject.bank_name = false;
                                return newObject;
                              });
                            }
                          }}
                          required={true}
                          error={errorListBank.bank_name}
                          value={bankDetails.bank_name}
                          customClass={style.customInputClass}
                        />
                      </div>
                      <div>
                        <p>Payment Reference No</p>
                        <InputText
                          placeholder="Enter Payment Reference No"
                          getValue={(value) => {
                            setBankDetails((prev) => {
                              let newObject = { ...prev };
                              newObject.reference_no = value;
                              return newObject;
                            });
                            if (value) {
                              setErrorListBank((prev) => {
                                let newObject = { ...prev };
                                newObject.reference_no = false;
                                return newObject;
                              });
                            }
                          }}
                          required={true}
                          error={errorListBank.reference_no}
                          value={bankDetails.reference_no}
                          customClass={style.customInputClass}
                        />
                      </div>
                    </div>
                  </>
                ) : (
                  <p className={style.bankError}>Bank Details Not Available</p>
                ))}
            </div>
          )}
        {totalStats.totalPrice > 0 && (
          <div className={`${style.discount_section} ${style.box_design}`}>
            <p>Discount Code</p>
            <div className={style.discount_input}>
              {!appliedDiscount.code ? (
                <>
                  <div>
                    <InputText
                      type="text"
                      getValue={(value) => {
                        console.log("value:", value);
                        setDiscount(value);
                      }}
                      placeholder="Enter discount code"
                      customCss={style.discountInput}
                    />
                  </div>
                  {!discountLoader ? (
                    <div>
                      <button
                        type="button"
                        className="secondary-btn"
                        onClick={() => discountCheck()}
                      >
                        Apply
                      </button>
                    </div>
                  ) : (
                    <div className="secondary-btn">
                      <Loader className={style.submitLoaderDiscount} />
                    </div>
                  )}
                </>
              ) : (
                <>
                  <div className={`${style.applied_discount}`}>
                    {appliedDiscount.code}
                  </div>
                  <div>
                    <button
                      type="button"
                      className="secondary-btn"
                      onClick={() => {
                        setAppliedDiscount({ code: "", percentage: "" });
                        dispatch(
                          checkoutStoreActions.updateDiscount({
                            discount: {
                              code: "",
                              percentage: "",
                              category: "",
                            },
                          })
                        );
                      }}
                    >
                      Clear
                    </button>
                  </div>
                </>
              )}
            </div>
            {discountMessage &&
              discountMessage.discount_message &&
              discountMessage.discount_message.content &&
              discountMessage.discount_message.content.length > 0 && (
                <div className={`${style.discount_message}`}>
                  {HtmlParser(discountMessage.discount_message.content[0])}
                </div>
              )}
            {discountErr && (
              <div className={`${style.discount_code_err}`}>{discountErr}</div>
            )}
          </div>
        )}
        <div className={style.total_calculation}>
          <div className={style.calculated_data}>
            {totalStats.totalPrice > 0 && (
              <>
                <div className={style.purchase_detail}>
                  {appliedDiscount.code ? (
                    <>
                      <div
                        className={`${style.purchase_data} ${style.color_dark}`}
                      >
                        <div className={`${style.purchase_title}`}>
                          {totalStats.itemCount} items :
                        </div>
                        <div
                          className={`${style.purchase_value} ${style.title_dark}`}
                        >
                          {totalStats.beforeDiscount} {currencyType}
                        </div>
                      </div>
                      <div
                        className={`${style.purchase_data} ${style.color_dark}`}
                      >
                        <div className={`${style.purchase_title}`}>
                          Discount ({appliedDiscount.percentage}% on{" "}
                          {totalStats.itemCount} items) :
                        </div>
                        <div
                          className={`${style.purchase_value} ${style.title_dark}`}
                        >
                          {totalStats.totalPrice} {currencyType}
                        </div>
                      </div>
                    </>
                  ) : (
                    <div
                      className={`${style.purchase_data} ${style.color_dark}`}
                    >
                      <div className={`${style.purchase_title}`}>
                        {totalStats.itemCount} items :
                      </div>
                      <div
                        className={`${style.purchase_value} ${style.title_dark}`}
                      >
                        {totalStats.totalPrice} {currencyType}
                      </div>
                    </div>
                  )}

                  <div className={`${style.purchase_data} ${style.color_dark}`}>
                    <div className={style.purchase_title}>
                      Delivery charge :
                    </div>
                    <div
                      className={`${style.purchase_value}  ${style.title_dark}`}
                    >
                      {totalStats.deliveryCharge} {currencyType}
                    </div>
                  </div>
                  {paymentMethod === "cash_on_delivery" &&
                    shipping &&
                    shipping.cod_charge &&
                    shipping.cod_charge > 0 && (
                      <div
                        className={`${style.purchase_data} ${style.color_dark}`}
                      >
                        <div className={style.purchase_title}>COD Charge :</div>
                        <div
                          className={`${style.purchase_value}  ${style.title_dark}`}
                        >
                          {totalStats.cod_charge} {currencyType}
                        </div>
                      </div>
                    )}
                  {totalStats.totalSaving > 0 && (
                    <div
                      className={`${style.purchase_data} ${style.color_dark}`}
                    >
                      <div
                        className={`${style.purchase_title} ${style.saving_text}`}
                      >
                        Total Savings ({totalStats.itemCount} items) :
                      </div>
                      <div
                        className={`${style.purchase_value}  ${style.title_dark}`}
                      >
                        {totalStats.totalSaving}
                        {currencyType}
                      </div>
                    </div>
                  )}
                </div>
                <hr />
                <div className={style.total}>
                  <div
                    className={`${style.purchase_detail} ${style.table_right}`}
                  >
                    <div
                      className={`${style.purchase_data} ${style.color_dark}`}
                    >
                      <div className={`${style.purchase_title}`}>
                        Grand Total :
                      </div>
                      {paymentMethod === "cash_on_delivery" ? (
                        <div
                          className={`${style.purchase_value}  ${style.title_dark}`}
                        >
                          {totalStats.grandTotal + totalStats.cod_charge}{" "}
                          {currencyType}
                        </div>
                      ) : (
                        <div
                          className={`${style.purchase_value}  ${style.title_dark}`}
                        >
                          {totalStats.grandTotal} {currencyType}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </>
            )}
          </div>
        </div>

        <div className={style.option_button}>
          <button
            type="button"
            className={`secondary-btn ${style.secondary_btn}`}
            onClick={() => onBackClicked()}
          >
            Back
          </button>
          <div></div>
          <div className={style.flex_data}>
            {/* <div className={style.purchase_detail}>
              {totalStats.totalPrice > 0 && (
                <>
                  <div className={style.purchase_data}>
                    <div
                      className={`${style.purchase_title} ${style.delivery_charge_text}`}
                    >
                      Delivery Charge :
                    </div>
                    <div className={`${style.purchase_value}`}>
                      {totalStats.deliveryCharge} {currencyType}
                    </div>
                  </div>
                  <div className={style.purchase_data}>
                    <div className={style.purchase_title}>Grand Total :</div>
                    <div className={style.purchase_value}>
                      {totalStats.grandTotal} {currencyType}
                    </div>
                  </div>
                </>
              )}
            </div> */}
            {loader ? (
              <div className={`primary_btn_no_animation ${style.primary_btn}`}>
                <Loader className={style.submitLoader} />
              </div>
            ) : (
              totalStats.totalPrice > 0 &&
              validation === true && (
                <>
                  {paymentMethod === "card(stripe)" && (
                    <button
                      type="button"
                      className={`primary_btn_no_animation ${style.primary_btn}`}
                      onClick={() => onSubmitClick("stripe")}
                    >
                      <Payment /> Payment
                    </button>
                  )}
                  {paymentMethod === "card(paytabs)" && (
                    <button
                      type="button"
                      className={`primary_btn_no_animation ${style.primary_btn}`}
                      onClick={() => onSubmitClick("paytabs")}
                    >
                      <Payment /> Payment
                    </button>
                  )}
                  {((paymentMethod === "bank" &&
                    bank_owner_details &&
                    bank_owner_details.iban_no) ||
                    paymentMethod === "cash_on_delivery") && (
                    <button
                      type="button"
                      className={`primary_btn_no_animation ${style.primary_btn}`}
                      onClick={() => onPendingPaymentMethodSubmit()}
                    >
                      Place Order
                    </button>
                  )}
                </>
              )
            )}
            {validation === false ? (
              <div className={style.error_message}>{error}</div>
            ) : (
              ""
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ReviewCheckout;
