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

import classNames from "classnames";
import { connect, useDispatch } from "react-redux";

import Spottable from "@enact/spotlight/Spottable";
import { setContainerLastFocusedElement } from "@enact/spotlight/src/container";

import { resetPanels } from "../../../../actions/panelActions";
import { panel_names } from "../../../../utils/Config";
import { SpotlightIds } from "../../../../utils/SpotlightIds";
import css from "./OnSaleNavItem.module.less";

const SpottableComponent = Spottable("li");

export default memo(function OnSaleNavItem({
  categoryInfos,
  categoryInfosItem,
  itemIndex,
  panelInfoLgCatCd,
  selectedLgCatCd,
  setFirstFocusableTarget,
  setSelectedLgCatCd,
  setSelectedLgCatNm,
  length,
  ...rest
}) {
  const dispatch = useDispatch();

  const { lgCatCd, lgCatNm } = categoryInfosItem;

  const selected = selectedLgCatCd
    ? selectedLgCatCd === lgCatCd && css.selected
    : panelInfoLgCatCd
      ? panelInfoLgCatCd === lgCatCd && css.selected
      : itemIndex === 0;

  const selectedText = selected === true ? "Selected, " : "";

  const ariaLabel =
    selectedText + lgCatNm + " tab, " + (itemIndex + 1) + " of " + length;

  const handleClick = useCallback(() => {
    if (!selectedLgCatCd && !panelInfoLgCatCd) {
      if (categoryInfos[0]?.lgCatCd === lgCatCd) return;
    } else {
      if (panelInfoLgCatCd === lgCatCd) return;
    }

    dispatch(resetPanels([{ name: panel_names.ON_SALE_PANEL }]));

    const body = document.querySelector(`[id="${SpotlightIds.TBODY}"]`);
    if (body) {
      setContainerLastFocusedElement(null, [
        body.getAttribute("data-spotlight-id"),
      ]);
    }
    setSelectedLgCatCd(lgCatCd);
    setSelectedLgCatNm(lgCatNm);
    setFirstFocusableTarget();
  }, [
    categoryInfos,
    dispatch,
    lgCatCd,
    lgCatNm,
    panelInfoLgCatCd,
    selectedLgCatCd,
    setFirstFocusableTarget,
    setSelectedLgCatCd,
    setSelectedLgCatNm,
  ]);

  return (
    <SpottableComponent
      className={classNames(
        css.item,
        selectedLgCatCd
          ? selectedLgCatCd === lgCatCd && css.selected
          : panelInfoLgCatCd
            ? panelInfoLgCatCd === lgCatCd && css.selected
            : itemIndex === 0 && css.selected
      )}
      onClick={handleClick}
      id={"spotlightId-" + lgCatCd}
      spotlightId={"spotlightId-" + lgCatCd}
      aria-label={ariaLabel}
      {...rest}
    >
      <figure>
        <div className={css["icon-" + lgCatCd]} />
      </figure>

      <strong>{lgCatNm}</strong>
    </SpottableComponent>
  );
});
