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

import { useDispatch } from "react-redux";

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

import defaultShowImage from "../../../../../assets/images/img-thumb-empty-product@3x.png";
import IcLiveShow from "../../../../../assets/images/tag/tag-liveshow.svg";
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,
  LOG_TP_NO,
  panel_names,
} from "../../../../utils/Config";
import { getTranslate3dValueByDirection } from "../../../../utils/helperMethods";
import { SpotlightIds } from "../../../../utils/SpotlightIds";
import css from "./SearchShowCard.module.less";

const CardContainer = Spottable("div");

export default memo(function SearchShowCard({
  contentId,
  idx,
  liveFlag,
  patncNm,
  searchQueryRef,
  spotlightId,
  thumbnail,
  title,
  ...rest
}) {
  const [firstChk, setFirstChk] = useState(0);

  const dispatch = useDispatch();

  const sendLog = (newParams) => {
    const logParams = {
      ...newParams,
      showTitle: title,
      showId: contentId.split("_").pop() || "",
      partner: patncNm,
      contextName: LOG_CONTEXT_NAME.SEARCH,
      messageId: LOG_MESSAGE_ID.SEARCH_RESULT_CLICK,
    };
    dispatch(sendLogTotalRecommend(logParams));
  };

  const handleShowClick = useCallback(
    (e) => {
      const tokkens = contentId && contentId.split("_");
      const linkTpCd = tokkens[1] || "";
      const patnrId = tokkens[4] || "";
      const showId = 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({
        contentId: showId,
        resultType: "show",
      });
      if (xContainer && yContainer) {
        const section = "search-show";
        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.PLAYER_PANEL,
          panelInfo: {
            patnrId,
            showId,
            chanId: showId,
            linkTpCd,
            thumbnail,
            shptmBanrTpNm: liveFlag === "Y" ? "LIVE" : "VOD",
          },
        })
      );

      dispatch(
        sendLogSearchClick({
          keyword: searchQueryRef.current,
          patncNm,
          patnrId,
          showId,
          showNm: title,
        })
      );
    },
    [contentId, 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 = "SHOW, 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("SHOW, Heading 2,", "");
          c.setAttribute("aria-label", newcAriaLabel);
        }
      }
    } else {
      return;
    }
  }, [firstChk]);

  return (
    <CardContainer
      className={css.card}
      onClick={handleShowClick}
      spotlightId={spotlightId}
      aria-label={"SHOW " + title}
      onFocus={handleFocus}
      {...rest}
    >
      <div className={css.innerWrapper}>
        <div className={css.imageBox}>
          {liveFlag === "Y" && (
            <span className={css.liveBadge}>
              <img src={IcLiveShow} alt="LIVE" />
            </span>
          )}

          <CustomImage
            alt={title}
            delay={0}
            src={thumbnail}
            fallbackSrc={defaultShowImage}
          />
        </div>
        <p className={css.title}>{title}</p>
      </div>
    </CardContainer>
  );
});
