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

import { useDispatch } from "react-redux";

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

import { pushPanel, updatePanel } from "../../../../actions/panelActions";
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 "./SearchThemeCard.module.less";
import {
  sendLogSearchClick,
  sendLogTotalRecommend,
} from "../../../../actions/logActions";

const ThemeContainer = Spottable("div");

export default memo(function SearchThemeCard({
  contentId,
  idx,
  keyword,
  patncNm,
  searchQueryRef,
  spotlightId,
  title,

  ...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));
  };
  const [firstChk, setFirstChk] = useState(0);

  const handleThemeClick = useCallback(
    (e) => {
      const tokkens = contentId && contentId.split("_");
      const themeType = tokkens[3] || "";
      const type = themeType === "TD" ? "theme" : "hotel";
      const patnrId = tokkens[4] || "";
      const curationId = tokkens[5] || "";
      const prdtId = tokkens[6] || "";

      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,
        resultType: type,
      });

      if (xContainer && yContainer) {
        const section = "search-theme";
        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: {
            prdtId,
            patnrId,
            curationId,
            type,
          },
        })
      );

      dispatch(
        sendLogSearchClick({
          curationId,
          curationNm: title,
          keyword: searchQueryRef.current,
          patncNm,
          patnrId,
        })
      );
    },
    [contentId, dispatch, idx, patncNm, title]
  );
  const keywordText = (keyword) => {
    let text = "";

    keyword.map((item) => (text += "#" + item));
    return text;
  };

  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 = "HOT PICKS, 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("HOT PICKS, Heading 2,", "");
          c.setAttribute("aria-label", newcAriaLabel);
        }
      }
    } else {
      return;
    }
  }, [firstChk]);

  const ariaLabel = title + ", " + keywordText(keyword);
  return (
    <ThemeContainer
      className={css.card}
      onClick={handleThemeClick}
      spotlightId={spotlightId}
      aria-label={ariaLabel}
      onFocus={handleFocus}
      {...rest}
    >
      <h2 className={css.title}>{title}</h2>
      <ul className={css.keywordWrap}>
        {keyword &&
          keyword.map((item, index) => (
            <li key={index} className={css.keywordList} aria-label={ariaLabel}>
              <span className={css.keyword}># {item}</span>
            </li>
          ))}
      </ul>
    </ThemeContainer>
  );
});
