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

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

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

import { setHidePopup, setShowPopup } from "../../../actions/commonActions";
import { popPanel } from "../../../actions/panelActions";
import TButton from "../../../components/TButton/TButton";
import TPopUp from "../../../components/TPopUp/TPopUp";
import * as Config from "../../../utils/Config";
import {
  $L,
  formatCurrencyValue,
  getErrorMessage,
} from "../../../utils/helperMethods";
import css from "./SummaryContainer.module.less";
import { sendLogTotalRecommend } from "../../../actions/logActions";

const Container = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  "div"
);

export default function SummaryContainer({
  setPlaceOrderPopup,
  empTermsData,
  handleTermsClick,
  currSign,
  currSignLoc,
  doSendLogPaymentEntry,
}) {
  const priceTotalData = useSelector(
    (state) => state.checkout?.checkoutTotalData
  );

  const productList = useSelector(
    (state) => state.checkout?.checkoutData.productList?.[0]
  );

  const dispatch = useDispatch();

  const items = useMemo(
    () => [
      {
        name: "Items",
        value: priceTotalData?.totProdPrc
          ? formatCurrencyValue(
              priceTotalData.totProdPrc,
              currSign,
              currSignLoc
            )
          : "-",
      },
      {
        name: "Your Coupon Savings",
        value: priceTotalData?.totDcAmt
          ? formatCurrencyValue(
              priceTotalData.totDcAmt,
              currSign,
              currSignLoc,
              true
            )
          : "-",
      },
      {
        name: "Shipping & Handling",
        value: priceTotalData?.totDlvrAmt
          ? formatCurrencyValue(
              priceTotalData.totDlvrAmt,
              currSign,
              currSignLoc
            )
          : "-",
      },
      {
        name: "TOTAL (before Tax)",
        value: priceTotalData?.ordPmtNoTaxAmt
          ? formatCurrencyValue(
              priceTotalData.ordPmtNoTaxAmt,
              currSign,
              currSignLoc
            )
          : "-",
      },
      {
        name: "Estimated Sales Tax",
        value: priceTotalData?.ordTotTaxAmt
          ? formatCurrencyValue(
              priceTotalData.ordTotTaxAmt,
              currSign,
              currSignLoc
            )
          : "-",
      },
    ],
    [priceTotalData, currSign, currSignLoc]
  );

  const handleClickOrder = useCallback(() => {
    if (doSendLogPaymentEntry) {
      doSendLogPaymentEntry();
    }
    dispatch(
      sendLogTotalRecommend({
        buttonTitle: "PLACE ORDER",
        buttonId: "checkout_place_order_view",
        contextName: Config.LOG_CONTEXT_NAME.CHECKOUT,
        messageId: Config.LOG_MESSAGE_ID.BUTTONCLICK,
      })
    );

    setPlaceOrderPopup(true);
  }, [doSendLogPaymentEntry, setPlaceOrderPopup]);

  const renderItemList = useCallback(
    () =>
      items.map((item, index) => (
        <div key={index} className={css.item}>
          <span className={css.summaryDesc}>{item.name}</span>
          <span className={css.summaryCnt}>{item.value}</span>
        </div>
      )),
    [items]
  );

  const renderTermsList = useCallback(
    () =>
      empTermsData &&
      empTermsData.length > 0 &&
      empTermsData.map((term) => {
        const { termsID, termsTypeName } = term;
        return (
          <li key={termsID} className={css.termsList}>
            <span className={css.termsTypeName}>{termsTypeName}</span>
            <TButton
              className={css.viewAllButton}
              onClick={() => handleTermsClick(termsID)}
            >
              {$L("View All")}
            </TButton>
          </li>
        );
      }),
    [empTermsData, handleTermsClick]
  );

  const estimatedTotal = useMemo(
    () =>
      priceTotalData?.ordPmtReqAmt
        ? formatCurrencyValue(
            priceTotalData.ordPmtReqAmt,
            currSign,
            currSignLoc
          )
        : "-",
    [priceTotalData, currSign, currSignLoc]
  );

  const showAuctionNotice =
    productList?.auctProdYn === "Y" && !productList.auctFinalPriceChgDt;

  return (
    <>
      <Container className={css.container}>
        <div className={css.order}>
          <h3>{$L("ORDER SUMMARY")}</h3>
          <span className={css.line} />
          <div className={css.itemWrap}>{renderItemList()}</div>
        </div>
        <div className={css.total}>
          <div className={css.totalBox}>
            <div className={css.totalTitle}>{$L("Estimated Total")}</div>
            <div className={css.price}>{estimatedTotal}</div>
          </div>
          {showAuctionNotice && (
            <div className={css.noticeBox}>
              {$L("Purchased products will be paid at the final price.")}
            </div>
          )}
        </div>
        <div className={css.bottom}>
          <ul className={css.termsWrap}>{renderTermsList()}</ul>
          <TButton
            className={css.tButton}
            onClick={handleClickOrder}
            spotlightId="spotlightId_placeOrderBtn"
          >
            {$L("PLACE ORDER")}
          </TButton>
        </div>
      </Container>
    </>
  );
}
