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

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

import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import { Cancelable } from "@enact/ui/Cancelable";

import { popPanel } from "../../actions/panelActions";
import { SpotlightIds } from "../../utils/SpotlightIds";
import SmoodShowingAnimation from "../SmoodShowingAnimation/SmoodShowingAnimation";
import css from "./TPanel.module.less";

const CancelablePanel = Cancelable(
  { modal: true, onCancel: "handleCancel" },
  SpotlightContainerDecorator({ enterTo: "last-focused" }, "div")
);

const PERFORMANCE_CHECHING_TIME = 200; //ms
const PERFORMANCE_CHECHING_COUNT = 7;
const TPanel = ({
  className,
  children,
  handleCancel,
  isTabActivated = true,
  spotlightId = SpotlightIds.TPANEL,
  isOnTop = false,
  ...rest
}) => {
  const dispatch = useDispatch();

  const isGnbOpened = useSelector((state) => state.common.isGnbOpened);
  const isLoading = useSelector((state) => state.common.appStatus.isLoading);

  const onCancel = useCallback(
    (e) => {
      if (isGnbOpened || isOnTop) {
        return;
      }
      if (handleCancel) {
        handleCancel(e);
      } else {
        dispatch(popPanel());
        e.stopPropagation();
      }
    },
    [dispatch, handleCancel, isTabActivated, isGnbOpened, isOnTop]
  );
  delete rest.panelInfo;

  return (
    <CancelablePanel
      {...rest}
      id={SpotlightIds.TPANEL}
      handleCancel={onCancel}
      className={classNames(
        css.tpanelmain,
        isTabActivated && css.isTabActivated,
        className
      )}
      spotlightId={spotlightId}
      spotlightDisabled={isLoading}
    >
      {children}
    </CancelablePanel>
  );
};

export default SmoodShowingAnimation(TPanel);
