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

import classNames from "classnames";

import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";

import useScrollTo from "../../hooks/useScrollTo";
import TButton from "../TButton/TButton";
import TScroller from "../TScroller/TScroller";
import css from "./TButtonScroller.module.less";

const Container = SpotlightContainerDecorator(
  { enterTo: "default-element" },
  "div"
);

export default function TButtonScroller({
  children,
  boxHeight,
  width,
  className,
  resetScrollPosition,
  forcedFocus = true,
  kind,
}) {
  const { getScrollTo, scrollTop } = useScrollTo();

  const scrollRef = useRef(null);
  const contentRef = useRef(null);
  const [contentHeight, setContentHeight] = useState(0);
  const [scrollVerticalPos, setScrollVerticalPos] = useState(0);
  const [checkScrollPosition, setCheckScrollPosition] = useState("top");

  useEffect(() => {
    calculateContentHeight();
  }, [children]);

  useEffect(() => {
    if (resetScrollPosition) {
      scrollTop({
        y: 0,
        animate: false,
      });
    }
  }, [resetScrollPosition]);

  const calculateContentHeight = useCallback(() => {
    if (contentRef.current) {
      const offsetTop = contentRef.current?.offsetTop;
      const offsetHeight = contentRef.current?.offsetHeight;

      setContentHeight(offsetTop + offsetHeight);
    }
  }, [contentRef]);

  const handleScrollUp = useCallback(() => {
    scrollTop({
      y: scrollVerticalPos - boxHeight,
      animate: false,
    });
  }, [boxHeight, scrollVerticalPos, checkScrollPosition]);

  const handleScrollDown = useCallback(() => {
    scrollTop({
      y: scrollVerticalPos + boxHeight,
      animate: false,
    });
  }, [boxHeight, scrollVerticalPos, checkScrollPosition]);

  const contentBoxStyle = useMemo(
    () => ({ width: `${width}px`, height: `${boxHeight}px` }),
    [width, boxHeight]
  );

  useEffect(() => {
    Spotlight.focus("tPopupBtn1");
  }, []);

  const disabledIndicator = useMemo(() => {
    return boxHeight >= contentHeight;
  }, [boxHeight, contentHeight]);

  useEffect(() => {
    if (!forcedFocus) return;

    if (checkScrollPosition === "top") {
      if (kind === "figmaTermsPopup") {
        Spotlight.focus("figma-terms-agree");
      } else {
        Spotlight.focus("spotlightId_TbuttonScrollerDown");
      }
    } else if (checkScrollPosition === "bottom") {
      if (kind === "figmaTermsPopup") {
        Spotlight.focus("figma-terms-agree");
      } else {
        Spotlight.focus("spotlightId_TbuttonScrollerUp");
      }
    }
  }, [checkScrollPosition, forcedFocus]);
  return (
    <Container
      spotlightId="spotlightId-scrllerCotainer"
      className={classNames(css.content, className && className)}
      style={contentBoxStyle}
      ref={scrollRef}
    >
      {!disabledIndicator && (
        <TButton
          className={classNames(
            css.upButton,
            css.arrowButton,
            (checkScrollPosition === "top" || disabledIndicator) &&
              css.upButtonDimmed
          )}
          onClick={handleScrollUp}
          spotlightDisabled={checkScrollPosition === "top" || disabledIndicator}
          spotlightId="spotlightId_TbuttonScrollerUp"
          aria-label="scroll Up"
          role="button"
        />
      )}
      <TScroller
        className={css.scrollContainer}
        verticalScrollbar={disabledIndicator ? "hidden" : "auto"}
        cbScrollTo={getScrollTo}
        setScrollVerticalPos={setScrollVerticalPos}
        setCheckScrollPosition={setCheckScrollPosition}
      >
        <div ref={contentRef} aria-label={children}>
          {children}
        </div>
      </TScroller>
      {!disabledIndicator && (
        <TButton
          className={classNames(
            css.downButton,
            css.arrowButton,
            (checkScrollPosition === "bottom" || disabledIndicator) &&
              css.downButtonDimmed
          )}
          onClick={handleScrollDown}
          spotlightDisabled={
            checkScrollPosition === "bottom" || disabledIndicator
          }
          spotlightId="spotlightId_TbuttonScrollerDown"
          aria-label="scroll Down"
          role="button"
        />
      )}
    </Container>
  );
}
