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 Spotlight from "@enact/spotlight";
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,
  onSpotlightLeft,
  spotlightDisabled = false,
  noMarquee,
  children,
  listType,
  colorType,
  spotlightId,
  scrollTop,
  onBlur,
  onFocus,
  ariaLabel,
  ...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(
    (e) => {
      setPressed(false);
      clearPressedJob.current.stop();

      if (onBlur) {
        onBlur(e);
      }
      setBlur(true);
    },
    [onBlur]
  );

  const _onFocus = useCallback(
    (e) => {
      if (onFocus) {
        onFocus(e);
      }
    },
    [onFocus]
  );

  const _onSpotlightLeft = useCallback(
    (e) => {
      if (onSpotlightLeft && index === 0) {
        onSpotlightLeft(e);
      }
    },
    [onSpotlightLeft, index]
  );

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

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

const TButtonTabItem = ImageItemDecorator(ItemBase);

export default TButtonTabItem;
