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

import css from "./TButton.module.less";

import { useCallback, useState } from "react";

import Spottable from "@enact/spotlight/Spottable";
import { Marquee, MarqueeController } from "@enact/ui/Marquee";

const SpottableComponent = Spottable("div");

function TButtonBase({
  children,
  spotlightId,
  className,
  onClick,
  onBlur,
  onFocus,
  disabled,
  selected,
  ...rest
}) {
  const [isFocused, setIsFocused] = useState(false);
  const [pressed, setPressed] = useState(false);

  const _onClick = useCallback(
    (e) => {
      if (disabled) {
        e.stopPropagation();
        return;
      }

      setPressed(true);

      if (onClick) {
        onClick(e);
      }
    },
    [onClick, disabled]
  );

  const _onFocus = useCallback(() => {
    setIsFocused(true);

    if (onFocus) {
      onFocus();
    }
  }, [onFocus]);

  const _onBlur = useCallback(() => {
    setIsFocused(false);

    if (onBlur) {
      onBlur();
    }
  }, [onBlur]);

  return (
    <SpottableComponent
      className={classNames(
        css.tButton,
        isFocused && css.focused,
        selected && css.selected
      )}
      spotlightId={spotlightId}
      onFocus={_onFocus}
      onBlur={_onBlur}
      onClick={_onClick}
    >
      <Marquee marqueeOn="focus">{children}</Marquee>
    </SpottableComponent>
  );
}

const ButtonDecorator = compose(MarqueeController({ marqueeOnFocus: true }));
const TButton = ButtonDecorator(TButtonBase);

export default TButton;
