import React, { useCallback, 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";

const SpottableComponent = Spottable("div");
const TabItemBase = ({
  selected = false,
  expanded = false,
  index = 0,
  title,
  target,
  deActivateTab,
  onClick,
  lgCatCd,
  isSubItem,
  onFocus,
  path,
  ...rest
}) => {
  const [focused, setFocused] = useState(false);
  const itemRef = useRef();

  const clearPressedJob = useRef(
    new Job((func) => {
      setTimeout(func, 100);
    }, 100)
  );
  const _onClick = useCallback(
    (ev) => {
      clearPressedJob.current.start(() => {
        if (onClick) {
          onClick({ index, target });
        }
      });
    },
    [target, index, onClick]
  );

  const _onFocus = useCallback(() => {
    setFocused(true);
    if (onFocus) {
      onFocus(index);
    }
  }, [index]);

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

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

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

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

  delete rest.hasChildren;
  delete rest.getChildren;
  return (
    <SpottableComponent
      ref={itemRef}
      className={classNames(
        css.tabItem,
        !path && focused && css.focused,
        path && css.path
      )}
      onKeyDown={onKeyDown}
      onFocus={_onFocus}
      onBlur={_onBlur}
      onClick={_onClick}
    >
      <div className={classNames(isSubItem && css.subWrap)}>
        {!path && (
          <span
            className={classNames(
              css.icon,
              focused && css.focused,
              css[`category-icon-${lgCatCd}`]
            )}
          />
        )}
        {path ? <ImageComponent /> : <TextComponent />}
      </div>
    </SpottableComponent>
  );
};
const ItemDecorator = compose(MarqueeController({ marqueeOnFocus: true }));
const TabItemSub = ItemDecorator(TabItemBase);

export default TabItemSub;
