import React, { useCallback, useRef, useState } from "react";

import classNames from "classnames";
import { useDispatch } from "react-redux";

import { Job } from "@enact/core/util";
import Spottable from "@enact/spotlight/Spottable";

import { popPanel, resetPanels } from "../../actions/panelActions";
import * as Config from "../../utils/Config";
import css from "./TIconButton.module.less";

const SpottableComponent = Spottable("div");

const SIZES = { tiny: "tiny", small: "small" };
const ICON_TYPES = {
  none: "none",
  back: "back",
  home: "home",
  leftArrow: "leftArrow",
  rightArrow: "rightArrow",
};

export default function TIconButton({
  className,
  iconType = ICON_TYPES.none,
  size = "normal",
  color,
  spotlightId = undefined,
  children,
  onClick,
  spotlightDisabled,
  disabled,
  ...rest
}) {
  const dispatch = useDispatch();

  const [pressed, setPressed] = useState(false);

  const clearPressedJob = useRef(
    new Job((func) => {
      setPressed(false);

      setTimeout(func, Config.TBUTTON_PRESS_DELAY);
    }, Config.TBUTTON_PRESS_DELAY)
  );

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

      setPressed(true);

      clearPressedJob.current.start(() => {
        if (onClick) {
          onClick(event);
        }

        switch (iconType) {
          case ICON_TYPES.back: {
            dispatch(popPanel());
            break;
          }

          case ICON_TYPES.home: {
            dispatch(resetPanels());
            break;
          }
        }
      });
    },
    [dispatch, iconType, onClick, disabled]
  );

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

    clearPressedJob.current.stop();
  }, []);

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

  return (
    <SpottableComponent
      spotlightId={spotlightId}
      className={classNames(
        css.tIconButton,
        css[iconType],
        css[size],
        disabled && css.disabled,
        className ? className : null,
        pressed && css.pressed
      )}
      onClick={_onClick}
      onBlur={_onBlur}
      onFocus={_onFocus}
      spotlightDisabled={spotlightDisabled}
      disabled={disabled}
      {...rest}
    >
      {children}
    </SpottableComponent>
  );
}

export { ICON_TYPES, SIZES };
