import React, { memo, useCallback, useEffect, useMemo, useState } from "react";

import classNames from "classnames";
import { useDispatch, useSelector } from "react-redux";

import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";

import { updateSelectedCoupon } from "../../../actions/checkoutActions";
import CustomImage from "../../../components/CustomImage/CustomImage";
import TDropDown from "../../../components/TDropDown/TDropDown";
import { $L, formatCurrencyValue } from "../../../utils/helperMethods";
import css from "./OffersPromotionItemCard.module.less";

const OffersPromotionItemContainer = SpotlightContainerDecorator(
  { leaveFor: { left: "", right: "" } },
  "div"
);
const DropDownBox = SpotlightContainerDecorator("div");
export const SIZES = {
  itemWidth: 660,
  itemHeight: 433,
  spacing: 12,
};

export default memo(function OffersPromotionItemCard({
  imgUrls,
  prdtNm,
  prodQty,
  prodtOpt,
  patncLogPath,
  prdtId,
  currSign,
  currSignLoc,
  shippingCharge,
  auctProdYn,
  auctFinalPriceChgDt,
  prdtCoupon,
  spotlightId,
  offerSideBarOpen,
  expsPrdtNo,
  ...rest
}) {
  const priceTotalData = useSelector(
    (state) => state.checkout?.checkoutTotalData
  );
  const selectedCoupon = useSelector(
    (state) => state.checkout?.selectedCoupons?.[prdtId]
  );

  const dispatch = useDispatch();
  const [openChk, setOpenChk] = useState(false);

  const selectedIndex = useMemo(() => {
    if (!selectedCoupon) return -1;
    return prdtCoupon.findIndex(
      (coupon) => coupon.cpnNo === selectedCoupon.cpnNo
    );
  }, [selectedCoupon, prdtCoupon]);

  const formattedPrices = useMemo(() => {
    return {
      discounted: priceTotalData?.totProdPrc
        ? formatCurrencyValue(priceTotalData?.totProdPrc, currSign, currSignLoc)
        : "-",

      shipping: priceTotalData?.totDlvrAmt
        ? formatCurrencyValue(priceTotalData?.totDlvrAmt, currSign, currSignLoc)
        : "-",
    };
  }, [priceTotalData, currSign, currSignLoc]);

  const handleCouponSelect = (e) => {
    const selectedIdx = e.selected;
    const selected = prdtCoupon[selectedIdx];
    dispatch(updateSelectedCoupon(prdtId, selected));
  };

  const dropDownOpen = useCallback(() => {
    setOpenChk(true);
  }, []);
  const dropDownClose = useCallback(() => {
    setOpenChk(false);
  }, []);

  useEffect(() => {
    const c = document.getElementById("floatLayer");
    c.classList.add("checkout_dropdown");
    return () => {
      c.classList.remove("checkout_dropdown");
    };
  }, []);
  useEffect(() => {
    if (offerSideBarOpen) {
      Spotlight.focus("fixed_dropdown");
    }
  }, [offerSideBarOpen]);

  return (
    <OffersPromotionItemContainer className={css.itemContainer}>
      <div className={css.itemHeader}>
        <CustomImage src={patncLogPath} alt="" className={css.patnrLogo} />
        <h2 className={css.prdtIt}>ID: {expsPrdtNo}</h2>
      </div>
      <div className={css.itemContents}>
        <div className={css.leftContents}>
          <CustomImage
            src={imgUrls[0].imgUrl}
            alt=""
            className={css.itemImage}
          />
        </div>
        <div className={css.rightContents}>
          <p className={css.prdtNm}>{prdtNm}</p>
          <p className={css.priceWrap}>
            <span className={css.itemPrice}>
              <span className={css.discountedPrice}>
                {formattedPrices.discounted}
              </span>
              {/* {originalPrice && originalPrice !== discountedPrice && (
                <span className={css.originalPrice}>
                  {formattedPrices.original}
                </span>
              )} */}
            </span>
            <span className={css.shippingPrice}>
              {`${$L("S&H")}: `}
              {formattedPrices.shipping}
            </span>
            {auctProdYn === "Y" && !auctFinalPriceChgDt && (
              <div className={css.noticeBox}>
                {$L("Purchased products will be paid at the final price.")}
              </div>
            )}
          </p>
        </div>
      </div>
      <DropDownBox className={css.dropDownWrap} spotlightId="fixed_dropdown">
        <TDropDown
          className={classNames(
            css.dropDown,
            openChk === true ? css.selected : null
          )}
          width="x-large"
          selectedIndex={selectedIndex}
          onSelect={handleCouponSelect}
          onOpen={dropDownOpen}
          onClose={dropDownClose}
        >
          {prdtCoupon.map((item) => item.cpnTtl)}
        </TDropDown>
      </DropDownBox>
    </OffersPromotionItemContainer>
  );
});
