import React, { ReactNode, useEffect, useRef } from 'react';
import classNames from 'classnames/bind';
import styles from './LayerContainer.scss';

const cx = classNames.bind(styles);

interface IOwnProps {
  onClose?: () => void;
  dimmedStyle?: React.CSSProperties | undefined;
  useDimmedColor?: boolean;
  children: ReactNode;
  style?: React.CSSProperties | undefined;
};

const LayerContainer: React.FC<IOwnProps> = ({ onClose, dimmedStyle, useDimmedColor, children, style }) => {
  const layerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const layerEl = layerRef.current;

    if (layerEl) {
      layerEl.dataset.isShow = 'true';

      setTimeout(() => {
        layerEl.dataset.isShow = 'false';
      }, 300);
    }
  }, []);

  const handleClickDimmed = (e: React.MouseEvent) => {
    const layerEl = layerRef.current;

    if (layerEl) {
      if (layerEl.dataset.isShow === 'true') {
        e.preventDefault();
        return;
      }

      onClose?.();
    }
  };

  return (
    <div className={cx('layer_container')} style={style}>
      <div className={cx('dimmed', useDimmedColor && 'color')} onClick={handleClickDimmed} style={dimmedStyle} ref={layerRef} />
      {children}
    </div>
  );
};

export default LayerContainer;
