import { Marquee, MarqueeController } from "@enact/sandstone/Marquee";
import Spottable from "@enact/spotlight/Spottable";
import { getTargetByDirectionFromElement } from "@enact/spotlight/src/target";
import classNames from "classnames";
import compose from "ramda/src/compose";
import { useCallback, useMemo, useRef, useState } from "react";
import css from "./TabItem.module.less";

const SpottableComponent = Spottable("div");
const TabItemBase = ({
  icons,
  title,
  expanded = false,
  selected = false,
  index = 0,
  deActivateTab,
  className,
  ...rest
}) => {
  const [focused, setFocused] = useState(false);
  const itemRef = useRef();

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

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

  const isDivider = useMemo(() => {
    return !title;
  }, []);
  const onKeyDown = useCallback(
    (event) => {
      if (event.key === "ArrowRight") {
        const next = getTargetByDirectionFromElement(
          "right",
          itemRef.current.node
        );
        if (!next && deActivateTab) {
          deActivateTab();
        }
      }
    },
    [deActivateTab]
  );
  const renderIcon = useCallback(() => {
    if (icons) {
      const Component = icons;
      return <Component iconType={focused ? "expanded" : "normal"} />;
    } else {
      return null;
    }
  }, [focused, selected, expanded]);
  return (
    <SpottableComponent
      ref={itemRef}
      className={classNames(
        css.tabItem,
        focused && css.focused
        //!isDivider && selected && css.selected
      )}
      onKeyDown={onKeyDown}
      onFocus={_onFocus}
      onBlur={_onBlur}
      spotlightDisabled={isDivider}
    >
      {icons && <div className={css.icon}>{renderIcon()}</div>}

      {expanded && title && (
        <Marquee marqueeOn={"focus"} className={classNames(css.text)}>
          {title}
        </Marquee>
      )}
    </SpottableComponent>
  );
};
const ItemDecorator = compose(MarqueeController({ marqueeOnFocus: true }));
const TabItem = ItemDecorator(TabItemBase);

export default TabItem;
