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

import classNames from "classnames";

import { off, on } from "@enact/core/dispatcher";
import { Job } from "@enact/core/util";
import Scroller from "@enact/sandstone/Scroller";

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

export default function TScroller({
  className,
  children,
  verticalScrollbar = "hidden",
  focusableScrollbar = false,
  direction = "vertical",
  horizontalScrollbar = "hidden",
  scrollMode,
  onScrollStart,
  onScrollStop,
  ...rest
}) {
  const isScrolling = useRef(false);
  const scrollPosition = useRef("top");

  const [onMoveScrollBarEffect, setOnMovevScrollBarEffect] = useState(false);
  const [isMounted, setIsMounted] = useState(false);

  const offMoveScrollBarEffect = new Job((func) => func(), 1000);

  useEffect(() => {
    setIsMounted(true);

    return () => setIsMounted(false);
  }, []);

  const handleWheel = useCallback(() => {
    if (!onMoveScrollBarEffect) {
      setOnMovevScrollBarEffect(true);

      offMoveScrollBarEffect.current.start(setOnMovevScrollBarEffect);
    } else {
      return;
    }
  }, [offMoveScrollBarEffect, onMoveScrollBarEffect]);

  useEffect(() => {
    on("wheel", handleWheel, document.getElementById("TScroller"));

    return () => {
      off("wheel", handleWheel, document.getElementById("TScroller"));
    };
  }, [handleWheel]);

  const _onScrollStart = useCallback(
    (e) => {
      if (onScrollStart) {
        onScrollStart(e);
      }

      isScrolling.current = true;
    },
    [onScrollStart]
  );

  const _onScrollStop = useCallback(
    (e) => {
      if (onScrollStop) {
        onScrollStop(e);
      }

      isScrolling.current = false;

      if (e.reachedEdgeInfo) {
        if (e.reachedEdgeInfo.top) {
          scrollPosition.current = "top";
        } else if (e.reachedEdgeInfo.bottom) {
          scrollPosition.current = "bottom";
        } else {
          scrollPosition.current = "middle";
        }
      } else {
        scrollPosition.current = "middle";
      }
    },
    [onScrollStop]
  );

  return (
    <Scroller
      {...rest}
      onScrollStart={_onScrollStart}
      onScrollStop={_onScrollStop}
      id="TScroller"
      scrollMode={scrollMode || "translate"}
      focusableScrollbar={focusableScrollbar}
      className={classNames(
        className,
        isMounted && css.tScroller,
        onMoveScrollBarEffect ? css.onMove : ""
      )}
      direction={direction}
      horizontalScrollbar={horizontalScrollbar}
      verticalScrollbar={verticalScrollbar}
      overscrollEffectOn={{
        arrowKey: false,
        drag: false,
        pageKey: false,
        track: false,
        wheel: false,
      }}
    >
      {children}
    </Scroller>
  );
}
