import React, { useCallback } from "react";

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

import { Panel } from "@enact/sandstone/Panels";
import { Cancelable } from "@enact/ui/Cancelable";

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

const CancelablePanel = Cancelable(
  { modal: true, onCancel: "handleCancel" },
  Panel
);

const TPanel = ({
  className,
  children,
  handleCancel,
  isTabActivated = true,
  ...rest
}) => {
  const dispatch = useDispatch();
  delete rest.panelInfo;

  const onCancel = useCallback(
    (e) => {
      if (isTabActivated) {
        return;
      }
      if (handleCancel) {
        handleCancel(e);
      } else {
        dispatch(popPanel());
        e.stopPropagation();
      }
    },
    [dispatch, handleCancel, isTabActivated]
  );

  return (
    <CancelablePanel
      {...rest}
      handleCancel={onCancel}
      className={classNames(
        css.tpanelmain,
        isTabActivated && css.isTabActivated,
        className
      )}
    >
      {children}
    </CancelablePanel>
  );
};

export default SmoodShowingAnimation(TPanel);
