import React, { useCallback, useEffect, useRef, useState } from "react";

import classNames from "classnames";
import compose from "ramda/src/compose";

import { Job } from "@enact/core/util";
import { Marquee, MarqueeController } from "@enact/sandstone/Marquee";
import Spottable from "@enact/spotlight/Spottable";

import css from "./TabItemSub.module.less";
import { sendLogTotalRecommend } from "../../actions/logActions";
import { LOG_CONTEXT_NAME, LOG_MESSAGE_ID } from "../../utils/Config";
import { useDispatch } from "react-redux";

const SpottableComponent = Spottable("div");

const TabItemBase = ({
  selected = false,
  expanded = false,
  index = 0,
  mainMenuTitle,
  title,
  target,
  deActivateTab,
  onClick,
  itemId,
  isSubItem,
  onFocus,
  path,
  patncNm,
  spotlightId,
  setLastFocusId,
  setSelectedTitle,
  setSelectedSubItemId,
  setSelectedSubIndex,
  label,
  ...rest
}) => {
  const [focused, setFocused] = useState(false);
  const dispatch = useDispatch();
  const itemRef = useRef();
  const clearPressedJob = useRef(new Job((func) => func(), 0));

  const _onClick = useCallback(
    (ev) => {
      const subtitle = title.split("-")[0];
      const buttonTitle = patncNm ? patncNm : subtitle;
      clearPressedJob.current.start(() => {
        if (itemId) {
          setSelectedSubItemId(itemId);
        }

        if (spotlightId) {
          setLastFocusId(spotlightId);
        }

        if (onClick) {
          onClick({ target, itemId });
        }

        dispatch(
          sendLogTotalRecommend({
            contextName: LOG_CONTEXT_NAME.GNB,
            messageId: LOG_MESSAGE_ID.GNB,
            buttonTitle: buttonTitle,
            buttonId: `GNB_CLICK_${buttonTitle.toUpperCase().replace(" ", "_")}`,
          })
        );
      });
    },
    [target, itemId, onClick, spotlightId, setSelectedSubItemId, setLastFocusId]
  );

  const _onFocus = useCallback(() => {
    setFocused(true);
    setSelectedSubItemId(null);
    setSelectedSubIndex(index);

    if (onFocus) {
      onFocus(index);
    }
  }, [index, onFocus, setSelectedSubItemId, setSelectedSubIndex]);

  const _onBlur = useCallback(() => {
    setFocused(false);
    setLastFocusId(null);
  }, [setLastFocusId]);

  const onKeyDown = useCallback(
    (event) => {
      if (event.key === "ArrowRight") {
        _onClick();
      }
    },
    [deActivateTab, target]
  );

  const ImageComponent = useCallback(() => {
    return (
      <>
        <div
          className={classNames(
            css.imageWrap,
            !focused && selected && css.selected,
            focused && selected && css.selectedFocus
          )}
        >
          <div
            className={classNames(css.iconContainer, focused && css.focused)}
          >
            <img src={path} alt="" />
            <h3>{patncNm}</h3>
          </div>
        </div>
      </>
    );
  }, [path, focused]);

  const TextComponent = useCallback(() => {
    const subtitle = title.split("-")[0];
    return (
      <>
        {subtitle && (
          <Marquee
            marqueeDisabled={!focused}
            marqueeOn={"focus"}
            className={classNames(css.text, isSubItem && css.subItem)}
          >
            {subtitle}
          </Marquee>
        )}
      </>
    );
  }, [title, focused, expanded]);

  delete rest.hasChildren;
  delete rest.getChildren;

  return (
    <SpottableComponent
      ref={itemRef}
      className={classNames(
        css.tabItem,
        path && css.featuredBrands,
        !path && focused && css.focused,
        !focused && !path && selected && css.selected,
        path && css.path
      )}
      onKeyDown={onKeyDown}
      onFocus={_onFocus}
      onBlur={_onBlur}
      onClick={_onClick}
      spotlightId={spotlightId}
      aria-label={
        patncNm
          ? selected && path
            ? "Selected Channel " + patncNm + " button " + label
            : "Channel " + patncNm + " button " + label
          : title.split("-")[0] + " Button " + label
      }
    >
      <div className={classNames(isSubItem && css.subWrap)}>
        {!path && (
          <span
            className={classNames(
              css.icon,
              focused && css.focused,
              !path && selected && css.selected,
              css[`category-icon-${itemId}`]
            )}
          />
        )}
        {path ? <ImageComponent /> : <TextComponent />}
      </div>
    </SpottableComponent>
  );
};
const ItemDecorator = compose(MarqueeController({ marqueeOnFocus: true }));
const TabItemSub = ItemDecorator(TabItemBase);

export default TabItemSub;
