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

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

import defaultLogoImg from "../../../../../../assets/images/ic-tab-partners-default@3x.png";
import defaultImageItem from "../../../../../../assets/images/img-thumb-empty-product@3x.png";
import { getMyinfoOrderCancelColumnsSearch } from "../../../../../actions/cancelActions";
import { setShowPopup, showError } from "../../../../../actions/commonActions";
import {
  getMyinfoOrderDetailSearch,
  getMyinfoOrderShippingSearch,
} from "../../../../../actions/orderActions";
import { pushPanel, updatePanel } from "../../../../../actions/panelActions";
import CustomImage from "../../../../../components/CustomImage/CustomImage";
import TButton from "../../../../../components/TButton/TButton";
import * as Config from "../../../../../utils/Config";
import { $L, formatCurrencyValue } from "../../../../../utils/helperMethods";
import {
  getStatusMessageAndClass,
  renderButtonsByStatus,
} from "../utils/orderStatus";
import css from "./OrderListCardStatus.module.less";

const ITEM_STATUS_TYPE = {
  cancel: "ORD003",
  exchange: "ORD004",
  return: "ORD005",
};

const LOG_STRING_CONF = {
  BUY_IT_AGAIN: "BUY IT AGAIN",
  CANCEL_ITEM: "CANCEL ITEM",
  RETURN_EXCHANGE_ITEM: "RETURN/EXCHANGE ITEM",
  TRACK_PACKAGE: "TRACK PACKAGE",
  VIEW_CANCELLATION_DETAILS: "VIEW CANCELLATION DETAILS",
  VIEW_ORDER_DETAILS: "VIEW ORDER DETAILS",
};

export default function OrderListCardStatus({
  orderProductInfo,
  paymentInfo,
  onClickBuyAgain,
  cancelItem,
  doSendLogOrderBtnClick,
  setSelectedCancelItem,
  ordNo,
  mbrNo,
}) {
  const {
    prdtId,
    shptmOrdStCd,
    shptmOrdStNm,
    logoImgPath,
    prdtNm,
    prdtImgUrl,
    prodQty,
    prdtOpt,
    prodPrc,
    prdtOptPrc,
    dlvrAmt,
    patnrId,
    auctProdYn,
    auctFinalPriceChgDt,
    patncNm,
    prodSno,
    patncPhnNo,
    stkCd,
    invTrceId,
    dlvrMeth,
    deliveryUrl,
    brndNm,
  } = orderProductInfo || {};

  const {
    cardKnd,
    cardNo,
    regDt,
    totProdQty,
    totProdPrc,
    totDcAmt,
    totOptPrc,
    totDlvrAmt,
    ordTotTaxAmt,
    currSign,
    currSignLoc,
    ordPmtReqAmt,
  } = paymentInfo || {};

  const dispatch = useDispatch();

  const { message, className } = useMemo(() =>
    getStatusMessageAndClass(shptmOrdStCd, shptmOrdStNm)
  );

  const _onClickBuyAgain = useCallback(
    (ev) => {
      onClickBuyAgain && onClickBuyAgain(ev);

      dispatch(
        pushPanel({
          name: Config.panel_names.DETAIL_PANEL,
          panelInfo: {
            patnrId,
            prdtId,
          },
        })
      );

      if (doSendLogOrderBtnClick) {
        doSendLogOrderBtnClick(LOG_STRING_CONF.BUY_IT_AGAIN);
      }
    },
    [dispatch, doSendLogOrderBtnClick, patnrId, prdtId, onClickBuyAgain]
  );

  const onClickCancelItem = useCallback(() => {
    dispatch(
      getMyinfoOrderCancelColumnsSearch(
        { reasonTpCd: ITEM_STATUS_TYPE.cancel },
        () => {
          dispatch(
            setShowPopup(Config.ACTIVE_POPUP.orderCancelPopup, {
              data: ordNo,
            })
          );
        }
      )
    );
    setSelectedCancelItem(orderProductInfo);
    if (doSendLogOrderBtnClick) {
      doSendLogOrderBtnClick(LOG_STRING_CONF.CANCEL_ITEM);
    }
  }, [dispatch, doSendLogOrderBtnClick, setSelectedCancelItem]);

  function showDetailPopup(response) {
    if (response) {
      if (response.retCode === 0) {
        if (
          response.data &&
          response.data.orderInfo &&
          response.data.orderInfo.length > 0
        ) {
          dispatch(setShowPopup(Config.ACTIVE_POPUP.orderDetailPopup));
        }
      } else {
        console.error("unknown Error", response);
      }
    }
  }

  const onClickViewOrderDetailsButton = useCallback(() => {
    if (auctProdYn === "Y" && !auctFinalPriceChgDt) {
      dispatch(
        showError(
          null,
          $L(
            "Order Details will be avilable once the payment is processed at the final price."
          )
        )
      );
    } else {
      dispatch(
        getMyinfoOrderDetailSearch({ ordNo, mbrNo, prdtId }, showDetailPopup)
      );

      if (doSendLogOrderBtnClick) {
        doSendLogOrderBtnClick(
          cancelItem
            ? LOG_STRING_CONF.VIEW_CANCELLATION_DETAILS
            : LOG_STRING_CONF.VIEW_ORDER_DETAILS
        );
      }
    }
  }, [
    auctProdYn,
    cancelItem,
    dispatch,
    doSendLogOrderBtnClick,
    orderProductInfo,
    showDetailPopup,
  ]);

  const onClickReturnExchange = useCallback(() => {
    dispatch(
      setShowPopup(Config.ACTIVE_POPUP.returnExchangePopup, {
        data: { patncNm, patncPhnNo },
      })
    );

    if (doSendLogOrderBtnClick) {
      doSendLogOrderBtnClick(LOG_STRING_CONF.RETURN_EXCHANGE_ITEM);
    }
  }, [dispatch, doSendLogOrderBtnClick]);

  const onClickTrackPackage = useCallback(() => {
    dispatch(
      setShowPopup(Config.ACTIVE_POPUP.trackPackagePopup, {
        data: { invTrceId, dlvrMeth, deliveryUrl },
      })
    );
  }, [dispatch]);

  return (
    <>
      <div className={css.itemListStatusContainer}>
        <div className={css.statusCardHeader}>
          <div className={css.wrap}>
            <span className={className}>{message}</span>
            <span className={css.arrivingDate}>
              {/* Arriving January 10 - January 15 */}
            </span>
          </div>
          <TButton
            size="small"
            className={css.viewOrderDetailsBtn}
            onClick={onClickViewOrderDetailsButton}
          >
            {cancelItem
              ? $L("VIEW CANCELLATION DETAILS")
              : $L("VIEW ORDER DETAILS")}
          </TButton>
        </div>
        <div className={css.statusCardBody}>
          <div className={css.productDetails}>
            <div className={css.productDetailsTitle}>
              <CustomImage
                src={logoImgPath}
                alt="Product logo"
                fallbackSrc={defaultLogoImg}
              />
              <h2 className={css.productName}>{prdtNm}</h2>
            </div>
            <div className={css.productDescWrap}>
              <div className={css.productImage}>
                <CustomImage
                  src={prdtImgUrl}
                  alt="Product Image"
                  fallbackSrc={defaultImageItem}
                />
              </div>
              <div className={css.productDesc}>
                <p>
                  {$L("ID")} : {stkCd}
                </p>
                <p>
                  {$L("Qty")} : {prodQty}
                </p>
                <p>
                  {prdtOpt && prdtOpt[0] && prdtOpt[0].optNm
                    ? `${prdtOpt[0].optNm} / `
                    : " "}
                  {prdtOpt && prdtOpt[0] && prdtOpt[0].prodOptCval
                    ? prdtOpt[0].prodOptCval
                    : " "}
                </p>
                <p className={css.price}>
                  <strong>
                    {formatCurrencyValue(ordPmtReqAmt, currSign, currSignLoc)}
                  </strong>{" "}
                  | {$L("S&H")}:{" "}
                  {formatCurrencyValue(totDlvrAmt, currSign, currSignLoc)}
                </p>
              </div>
            </div>
          </div>
          <div className={css.actionButtons}>
            {useMemo(() =>
              renderButtonsByStatus(shptmOrdStCd, ordNo, {
                _onClickBuyAgain,
                onClickCancelItem,
                onClickReturnExchange,
                onClickTrackPackage,
              })
            )}
          </div>
        </div>
      </div>
    </>
  );
}
