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

import { useDispatch } from "react-redux";

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

import defaultImageItem from "../../../../../assets/images/img-thumb-empty-product@3x.png";
import {
  sendLogSearchClick,
  sendLogTotalRecommend,
} from "../../../../actions/logActions";
import { pushPanel, updatePanel } from "../../../../actions/panelActions";
import CustomImage from "../../../../components/CustomImage/CustomImage";
import {
  LOG_CONTEXT_NAME,
  LOG_MESSAGE_ID,
  panel_names,
} from "../../../../utils/Config";
import { getTranslate3dValueByDirection } from "../../../../utils/helperMethods";
import { SpotlightIds } from "../../../../utils/SpotlightIds";
import css from "./SearchItemCard.module.less";

const ItemContainer = Spottable("div");

const parsePrice = (priceString) => {
  if (!priceString) {
    return "";
  }

  // US, GB, DE
  const formattedPriceCommon = priceString.slice(2).replace(/[.,]/g, "");

  // RU
  const formattedPriceRU = priceString.replace(/\s/g, "").replace(",", ".");

  return isNaN(priceString[0])
    ? parseFloat(formattedPriceCommon)
    : parseFloat(formattedPriceRU);
};

export default memo(function SearchItemCard({
  contentId,
  dcPrice,
  dataSize,
  idx,
  patncNm,
  price,
  searchQueryRef,
  spotlightId,
  thumbnail,
  title,
  length,
  ...rest
}) {
  const dispatch = useDispatch();
  const sendLog = (newParams) => {
    const logParams = {
      ...newParams,
      contextName: LOG_CONTEXT_NAME.SEARCH,
      messageId: LOG_MESSAGE_ID.SEARCH_RESULT_CLICK,
    };
    dispatch(sendLogTotalRecommend(logParams));
    console.log("###logParams", logParams);
  };

  const [firstChk, setFirstChk] = useState(0);

  const priceNumber = useMemo(() => parsePrice(price), [price]);
  const discountPriceNumber = useMemo(() => parsePrice(dcPrice), [dcPrice]);

  const handleItemClick = useCallback(
    (e) => {
      const tokkens = contentId && contentId.split("_");
      const patnrId = tokkens[4] || "";
      const prdtId = tokkens[5] || "";

      const tItemCard = e.currentTarget;
      const tBody = document.querySelector(`[id="${SpotlightIds.TBODY}"]`);

      const xContainer = tItemCard?.parentNode?.parentNode;
      const yContainer = tBody?.children[0]?.children[0]?.children[0];
      sendLog({
        productId: prdtId,
        productTitle: title,
        partner: patncNm,
        price: dcPrice ? dcPrice : price,
        resultType: "item",
      });
      if (xContainer && yContainer) {
        const section = "search-item";
        const x = getTranslate3dValueByDirection(xContainer);
        const y = yContainer.scrollTop;
        const c = Spotlight.getCurrent();
        let targetSpotlightId = null;

        if (c) {
          targetSpotlightId = c.getAttribute("data-spotlight-id");
        }

        dispatch(
          updatePanel({
            name: panel_names.SEARCH_PANEL,
            panelInfo: {
              currentSpot: targetSpotlightId,
              section,
              x,
              y,
              exprOrd: idx,
            },
          })
        );
      }

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

      dispatch(
        sendLogSearchClick({
          dcAfPrice: dcPrice,
          keyword: searchQueryRef.current,
          patncNm,
          patnrId,
          prdtId,
          prdtNm: title,
        })
      );
    },
    [contentId, dcPrice, dispatch, idx, patncNm, searchQueryRef, title]
  );

  const handleFocus = useCallback(() => {
    const c = Spotlight.getCurrent();
    const dataIndex = c.getAttribute("data-index");
    if (firstChk === 0 && dataIndex === "0") {
      if (c) {
        let cAriaLabel = c.getAttribute("aria-label");
        cAriaLabel = "Items, Heading 2," + cAriaLabel;
        c.setAttribute("aria-label", cAriaLabel);
      }
      setFirstChk(1);
    } else if (firstChk === 1 && dataIndex === "0") {
      const c = Spotlight.getCurrent();
      if (c) {
        let cAriaLabel = c.getAttribute("aria-label");
        if (cAriaLabel) {
          const newcAriaLabel = cAriaLabel.replace("Items, Heading 2,", "");
          c.setAttribute("aria-label", newcAriaLabel);
        }
      }
    } else {
      return;
    }
  }, [firstChk]);

  const priceText =
    price !== dcPrice && parseFloat(price) > parseFloat(dcPrice)
      ? `, Sale Price ${dcPrice}, Original price ${price}`
      : `, Price ${dcPrice}`;
  const ariaLabel =
    title +
    priceText +
    (idx * 1 + 1) +
    " of " +
    dataSize +
    ", go to details, button";

  return (
    <ItemContainer
      className={css.card}
      {...rest}
      onClick={handleItemClick}
      spotlightId={spotlightId}
      aria-label={ariaLabel + "___test" + idx}
      onFocus={handleFocus}
    >
      <div className={css.imageBox}>
        <CustomImage
          alt={title}
          delay={0}
          src={thumbnail}
          fallbackSrc={defaultImageItem}
        />
      </div>
      <div className={css.infoWrap}>
        <p
          className={css.title}
          dangerouslySetInnerHTML={{
            __html: `${title}`,
          }}
        />
        <div className={css.priceWrap}>
          {priceNumber > discountPriceNumber && (
            <span className={css.price}>{price}</span>
          )}
          <strong className={css.dcPrice}>{dcPrice}</strong>
        </div>
      </div>
    </ItemContainer>
  );
});
