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 * as Config from "../../utils/Config";
import { convertNewlinesToBr } from "../../utils/helperMethods";
import css from "./TButtonTabItem.module.less";

const SpottableComponent = Spottable("div");

const ItemBase = ({
  panelInfo,
  selected,
  onClick,
  index,
  selectedTabIndex,
  spotlightDisabled = false,
  noMarquee,
  children,
  listType,
  ...rest
}) => {
  const [pressed, setPressed] = useState(false);
  const [blur, setBlur] = useState(true);

  const _onClick = useCallback(
    (e) => {
      if (onClick) {
        onClick(e);
        setPressed(true);
        clearPressedJob.current.start();
      }
    },
    [onClick]
  );

  const clearPressedJob = useRef(
    new Job((func) => {
      setPressed(false);
      setTimeout(func, Config.TBUTTON_PRESS_DELAY);
    }, Config.TBUTTON_PRESS_DELAY)
  );

  const _onBlur = useCallback(() => {
    setPressed(false);
    clearPressedJob.current.stop();
    setBlur(true);
  }, [pressed]);

  const _onFocus = useCallback(() => {
    setBlur(false);
  }, [blur]);

  return (
    <SpottableComponent
      {...rest}
      className={classNames(
        css.tItem,
        selected && css.selected,
        pressed && css.pressed,
        css[listType]
      )}
      onClick={_onClick}
      spotlightDisabled={spotlightDisabled}
      spotlightId={`tab-${selectedTabIndex}`}
    >
      {noMarquee ? (
        <div className={css.title}>{convertNewlinesToBr(children)}</div>
      ) : (
        <Marquee
          className={css.title}
          alignment={"center"}
          marqueeOn={!blur ? "focus" : undefined}
          onFocus={_onFocus}
          onBlur={_onBlur}
        >
          {children}
        </Marquee>
      )}
    </SpottableComponent>
  );
};

const ImageItemDecorator = compose(
  MarqueeController({ mmarqueeOnFocus: true })
);

const TButtonTabItem = ImageItemDecorator(ItemBase);

export default TButtonTabItem;
