import React, { useEffect, useRef, useState } from "react";
import { YouMayAlsoLike } from "./components/youMayAlsoLike";
import { useAppDispatch, useAppSelector } from "../../../../../app/redux/hooks";
import { Button } from "@mui/material";
import { SkuValues } from "../../productDescription/productDescriptionTypes";
import CustomInput from "../../../../components/custom/input";
import CustomButton from "../../../../components/custom/button";
import { Link, useNavigate } from "react-router-dom";
import ShoppingCartCheckoutIcon from "@mui/icons-material/ShoppingCartCheckout";
import { showSnackbar } from "../../../../../app/slices/common/customSnackBar/customSnackbarSlice";
import {
  addOrUpdateCartAsync,
  fetchCartListAsync,
  removeItemFromCartAsync,
} from "../../../../../app/slices/cartSlice/CartSlice";
import ConfirmationDialog from "../../../../components/custom/confirm";
import CustomDialog from "../../../../components/custom/dialog";
import { CouponComponent } from "../../../private/chekout/components/myCart/CouponCodes";
import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination, Navigation } from "swiper/modules";
interface ShopingCartProps {
  onClose: any;
}
export const ShopingCart: React.FC<ShopingCartProps> = ({ onClose }) => {
  const [dialogOpen, setDialogOpen] = useState(false);
  const [confirmId, setConfirmId] = useState("");
  const navigate = useNavigate();

  const dispatch = useAppDispatch();
  const [quantities, setQuantities] = useState<{ [skuId: number]: number }>({});
  const { addTocart } = useAppSelector((state) => state.CartState);
  const billingData = addTocart.billingData;
  const [modalType, setModalType] = useState("");
  const swiperRef = useRef(null);
  const [selectedSku, setSelectedSku] = useState<SkuValues | null>(null);

  useEffect(() => {
    const quantities = addTocart?.data?.reduce((acc: any, item: any) => {
      acc[item.sku_id] = item.quantity;
      return acc;
    }, {});
    setQuantities(quantities);
  }, [addTocart?.data]);
  // Ensure `maxQuantity` is a valid number even if `sku_quantity` is undefined.
  const handleQuantityChange = (
    skuId: number | undefined,
    action: "increase" | "decrease",
    cart_item_id: number
  ) => {
    if (skuId === undefined) return;

    setQuantities((prevQuantities) => {
      const currentQuantity = prevQuantities[skuId] || 0;
      // const skus = addTocart?.data?.find((item: any) => item.sku_id === skuId); // Retrieve the SKU data
      const maxQuantity =
        // skuData?.sku_quantity ??
        Infinity; // Use Infinity if sku_quantity is undefined

      const newQuantity =
        action === "increase"
          ? Math.min(currentQuantity + 1, maxQuantity) // Increase quantity but limit to maxQuantity
          : Math.max(currentQuantity - 1, 0); // Decrease quantity but don't go below 0

      // If quantity reached 0 after decreasing, remove the item
      if (newQuantity === 0) {
        dispatch(removeItemFromCartAsync(cart_item_id)).then(
          (response: any) => {
            if (response?.payload?.status === 200) {
              // dispatch(fetchCartListAsync());
              const aId = localStorage.getItem("aId");
              const accessToken = localStorage.getItem("accessToken");
              const anonymous_id = accessToken ? null : aId ? aId : null;

              dispatch(fetchCartListAsync(anonymous_id));
            }
          }
        );
      } else if (newQuantity !== currentQuantity) {
        const updatedQuantities = Object.entries(prevQuantities).map(
          ([sku, quantity]) => {
            if (Number(sku) === skuId) {
              return { sku: Number(sku), quantity: newQuantity }; // Update the targeted SKU
            } else {
              return { sku: Number(sku), quantity }; // Keep the other SKUs unchanged
            }
          }
        );

        const payload: any = {
          skus: updatedQuantities, // Updated SKUs with quantities
        };
        const aId = localStorage.getItem("aId");
        const accessToken = localStorage.getItem("accessToken");
        if (aId && accessToken == null) {
          payload.anonymous_id = aId;
        }
        dispatch(addOrUpdateCartAsync(payload));
      }
      return {
        ...prevQuantities,
        [skuId]: newQuantity, // Update the quantity for the SKU
      };
    });
  };
  const openDialog = (id: any) => {
    setConfirmId(id);
    setDialogOpen(true);
  };

  const closeDialog = () => {
    setConfirmId("");
    setDialogOpen(false);
  };
  const confirmAction = () => {
    handleRemoveClick(confirmId);
    closeDialog();
  };
  const handleRemoveClick = (cart_item_id: any) => {
    dispatch(removeItemFromCartAsync(cart_item_id)).then((response: any) => {
      if (response?.payload?.status === 200) {
        dispatch(
          showSnackbar({
            message: "Item removed succesfuly.",
            severity: "success",
            autoHide: 2000,
          })
        );
        // dispatch(fetchCartListAsync());
        const aId = localStorage.getItem("aId");
        const accessToken = localStorage.getItem("accessToken");
        const anonymous_id = accessToken ? null : aId ? aId : null;

        dispatch(fetchCartListAsync(anonymous_id));
      } else {
        dispatch(
          showSnackbar({
            message: "Please try again later.",
            severity: "error",
            autoHide: 3000,
          })
        );
      }
    });
  };
  const onCloseModal = () => {
    setModalType("");
  };

  const removeCoupon = () => {
    const payload: any = {
      skus: Object.entries(quantities)?.map(([sku, quantity]) => ({
        sku: Number(sku),
        quantity,
      })),
      remove_coupon: true,
    };
    dispatch(addOrUpdateCartAsync(payload));
  };
  const handleBulletClick = (swiper: any) => {
    const activeIndex = swiper.realIndex;
    // NEED TO CHANGE
    // selectSku(productData?.skus[activeIndex]);
  };
  const selectSku = (sku: any) => {
    setSelectedSku(sku);
  };
  return (
    <>
      <div className="fullRight  modal-shopping-cart">
        <div className="modal-content">
          <div className="wrap">
            <div className="tf-mini-cart-threshold">
              <div className="tf-progress-bar">
                <span style={{ width: "50%" }}></span>
              </div>
              <div className="tf-progress-msg">
                Buy <span className="price fw-6">₹75.00</span> more to enjoy
                <span className="fw-6">Free Shipping</span>
              </div>
            </div>
            <div className="tf-mini-cart-wrap">
              <div className="tf-mini-cart-main">
                <div className="tf-mini-cart-sroll">
                  <div className="tf-mini-cart-items">
                    {addTocart?.data?.map((item: any) => {
                      return (
                        <div className="tf-mini-cart-item" key={item.sku_id}>
                          <div className="tf-mini-cart-image">
                            <div style={{ width: "80px", height: "80px" }}>
                              <img
                                src={`${process.env.REACT_APP_API_URL}${item?.product_image}`}
                                alt=""
                                style={{
                                  width: "100%",
                                  height: "100%",
                                  objectFit: "cover",
                                }}
                              />
                            </div>
                          </div>
                          <div className="tf-mini-cart-info">
                            <div className="title">{item?.product_name}</div>
                            {/* <a className="title link" href="#"> */}
                            <span
                              style={{ fontSize: "14px", lineHeight: "14px" }}
                            >
                              {item?.sku_name}-{item?.sku_quantity}{" "}
                              {item?.sku_unit}
                            </span>
                            {/* </a> */}
                            <div className="price fw-6">
                              ₹{item?.offer_price}
                            </div>
                            <div className="tf-mini-cart-btns">
                              <div className="wg-quantity small">
                                <Button
                                  onClick={() =>
                                    handleQuantityChange(
                                      item.sku_id,
                                      "decrease",
                                      item.cart_item_id
                                    )
                                  }
                                  disabled={addTocart?.loader}
                                  className="btn-quantity minus-btn"
                                  style={{
                                    cursor:
                                      quantities[item.sku_id] > 0
                                        ? "pointer"
                                        : "not-allowed",
                                  }}
                                >
                                  -
                                </Button>
                                <input
                                  type="text"
                                  value={quantities[item.sku_id] || 0}
                                  readOnly
                                />
                                <Button
                                  disabled={addTocart?.loader}
                                  onClick={() =>
                                    handleQuantityChange(
                                      item.sku_id,
                                      "increase",
                                      item.cart_item_id
                                    )
                                  }
                                  className="btn-quantity plus-btn"
                                >
                                  +
                                </Button>
                              </div>
                              <div
                                className="tf-mini-cart-remove"
                                onClick={
                                  () => openDialog(item.cart_item_id)
                                  // handleRemoveClick(item.cart_item_id)
                                }
                                style={{ cursor: "pointer" }}
                              >
                                Remove
                              </div>
                              <ConfirmationDialog
                                title="Confirm Action"
                                open={dialogOpen}
                                onClose={closeDialog}
                                onConfirm={confirmAction}
                                content="Are you sure you want to remove this item from cart?"
                              />
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                  {/* <div className="modal-shopping-cart">
                    <div
                      className="tf-minicart-recommendations"
                      style={{ marginLeft: "1%" }}
                    >
                      <div className="tf-minicart-recommendations-heading row">
                        <div
                          className="tf-minicart-recommendations-title"
                          style={{ width: "50%" }}
                        >
                          You may also like
                        </div>
                        <div className="sw-dots mt-0 small style-2 cart-slide-pagination2"></div>
                      </div>

                      <Swiper
                        modules={[Pagination, Navigation]}
                        onSwiper={(swiper: any) => (swiperRef.current = swiper)}
                        onSlideChange={handleBulletClick}
                        spaceBetween={10}
                        slidesPerView={1}
                        pagination={{
                          el: ".cart-slide-pagination2",
                          clickable: true,
                        }}
                        navigation={false}
                        className="tf-cart-slide2"
                      >
                        <SwiperSlide>
                          <div className="tf-minicart-recommendations-item">
                            <div className="tf-minicart-recommendations-item-image">
                              <a href="#">
                                <img
                                  src="images/product012.png"
                                  alt="Bread Atta"
                                  style={{ width: "70%" }}
                                />
                              </a>
                            </div>
                            <div className="tf-minicart-recommendations-item-infos flex-grow-1">
                              <a className="title" href="#">
                                Bread Atta
                              </a>
                              <div className="price">₹55.00</div>
                            </div>
                            <div className="tf-minicart-recommendations-item-quickview">
                              <div className="btn-show-quickview quickview hover-tooltip">
                                <span className="icon icon-view"></span>
                              </div>
                            </div>
                          </div>
                        </SwiperSlide>

                        <SwiperSlide>
                          <div className="tf-minicart-recommendations-item">
                            <div className="tf-minicart-recommendations-item-image">
                              <a href="#">
                                <img
                                  src="images/product013.png"
                                  alt="Pazham Chips"
                                  style={{ width: "70%" }}
                                />
                              </a>
                            </div>
                            <div className="tf-minicart-recommendations-item-infos flex-grow-1">
                              <a className="title" href="#">
                                Pazham Chips
                              </a>
                              <div className="price">₹125.00</div>
                            </div>
                            <div className="tf-minicart-recommendations-item-quickview">
                              <div className="btn-show-quickview quickview hover-tooltip">
                                <span className="icon icon-view"></span>
                              </div>
                            </div>
                          </div>
                        </SwiperSlide>
                      </Swiper>
                    </div>
                  </div> */}
                </div>
              </div>
              <div className="tf-mini-cart-bottom">
                <div className="tf-mini-cart-bottom-wrap">
                  {/* commented on 12/02  */}
                  {/* <div className="coupon-box">
                      <CustomInput
                        label="Coupon code"
                        name="couponcode"
                        size="small"
                        variant="outlined"
                        fullWidth
                      />
                      <CustomButton size="small" name="Apply" />
                    </div>
                    <div className="tf-page-cart-note">
                      <textarea
                        name="note"
                        id="cart-note"
                        placeholder="''Add Suggestions? we will pass on..''"
                      ></textarea>
                    </div> */}
                  {localStorage.getItem("accessToken") !== "" &&
                    localStorage.getItem("accessToken") !== null &&
                    localStorage.getItem("accessToken") !== undefined &&
                    addTocart?.data?.length > 0 && (
                      <>
                        <a
                          className="tf-btn  animate-hover-btn radius-3 w-100 justify-content-center orange-b btn-add-note orange-txt"
                          onClick={() => setModalType("couponCode")}
                        >
                          <span>
                            <i className="fa fa-birthday-cake"></i> Apply Coupon
                          </span>
                        </a>
                        {billingData?.coupon_code && (
                          <div className="coupon-d">
                            <div className="row align-items-center justify-content-between">
                              <div className="col-8">
                                <p>
                                  {billingData?.coupon_code} <br />
                                  <small
                                    style={{
                                      fontSize: "12px",
                                      color: "#ccc",
                                    }}
                                  >
                                    Offer applied on the bill
                                  </small>
                                </p>
                              </div>
                              <div className="col-4 text-end">
                                <a onClick={() => removeCoupon()}>
                                  <b>REMOVE</b>
                                </a>
                              </div>
                            </div>
                          </div>
                        )}
                      </>
                    )}
                  {/* <div className="tf-page-cart-note">
                      <textarea
                        name="note"
                        rows={1}
                        id="cart-note"
                        placeholder="''Add Suggestions? we will pass on..''"
                      ></textarea>
                    </div> */}
                  <h3 className="mt-3">Bill Details</h3>
                  <div className="tf-cart-totals-discounts">
                    <div className="tf-cart-total">Item Total</div>
                    <div className="tf-totals-total-value fw-6">
                      ₹{billingData.subtotal}
                    </div>
                  </div>
                  {/* <div className="tf-cart-totals-discounts">
                    <div>Delivery fee for 1.2 kms</div>
                    <div>
                      <s>₹{billingData.delivery_fee}</s>{" "}
                      <span className="orange-txt">FREE</span>
                    </div>
                  </div> */}
                  <div className="tf-cart-totals-discounts">
                    <div>Delivery </div>
                    <div>₹{billingData.delivery_fee} </div>
                  </div>
                  <hr />
                  {/* <div className="tf-cart-totals-discounts">
                    <div>Delivery Tip</div>
                    <div>
                      <a href="#" className="orange-txt">
                        Add tip
                      </a>
                    </div>
                  </div> */}
                  {/* <div className="tf-cart-totals-discounts">
                    <div>Platform Fee</div>
                    <div>₹10.00</div>
                  </div> */}
                  <div className="tf-cart-totals-discounts">
                    <div>GST and Restaurant charges</div>
                    <div>₹{billingData.taxes_and_charges}</div>
                  </div>
                  <hr />
                  <div className="tf-cart-totals-discounts">
                    <div className="tf-cart-total fw-6">To Pay</div>
                    <div className="tf-totals-total-value fw-6">
                      ₹{billingData.grand_total}
                    </div>
                  </div>
                  {/* commented on 12/02  */}
                  <div className="tf-mini-cart-view-checkout">
                    <div className="tf-btn animate-hover-btn radius-3 w-100 justify-content-center orange-b btn-add-note">
                      <span>Savings of ₹{billingData.total_savings}</span>
                    </div>
                  </div>{" "}
                  {/* <Link style={{ width: "100%" }} to="/checkout"> */}
                  <div className="tf-mini-cart-view-checkout">
                    {" "}
                    <CustomButton
                      size="medium"
                      endIcon={<ShoppingCartCheckoutIcon />}
                      fullWidth
                      name="Checkout"
                      disabled={
                        addTocart?.data === null ||
                        (Array.isArray(addTocart?.data) &&
                          addTocart?.data?.length === 0)
                      }
                      onClick={(e: void) => {
                        if (
                          addTocart?.data !== null &&
                          Array.isArray(addTocart?.data) &&
                          addTocart?.data?.length >= 0
                        ) {
                          navigate("/checkout");
                        }
                      }}
                    />
                  </div>{" "}
                  {/* </Link> */}
                  <div className="mt-2">
                    <p>
                      <b>
                        Review your order and address details to avoid
                        cancellations.
                      </b>
                    </p>
                    <p>
                      Note: Please ensure your address and order details are
                      correct. This order, if cancelled, is no refundable
                    </p>
                    <p>
                      <a href="#" className="orange-txt">
                        <b>Read Policy</b>
                      </a>
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <CustomDialog
        component={
          <CouponComponent modalType={modalType} onCloseModal={onCloseModal} />
        }
        title=""
        openDialog={modalType === "couponCode"}
        handleCloseDialog={onCloseModal}
        modalPlace="right"
      />
    </>
  );
};
