import React, { useEffect, useRef } from 'react';
import CloseSvg from '../../../assets/CloseSvg';
import s from './ModalComponent.module.scss';

type ModalComponentT = {
  children: React.ReactNode;
  closeFunc?: any;
  otherClassForWrapper?: any;
  position?: any;
};
export const ModalComponent = ({ ...props }: ModalComponentT) => {
  const { children, closeFunc, otherClassForWrapper, position } = props;
  let top, left, actualTop;
  if (position) {
    const windowHeight = window.innerHeight;
    top = position.e.clientY;
    left = position.e.clientX - 350;
    if (windowHeight - top <= 350) {
      actualTop = top - 350;
    } else {
      actualTop = top;
    }
  }

  const wrapperRef: any = useRef(null);
  useEffect(() => {
    if (closeFunc) {
      const handleClickOutside =
        (wrapperRef: any, closeFunc: any) => (event: any) => {
          if (
            wrapperRef.current &&
            !wrapperRef.current.contains(event.target)
          ) {
            closeFunc();
          }
        };
      document.addEventListener(
        'mousedown',
        handleClickOutside(wrapperRef, closeFunc)
      );

      return () => {
        document.removeEventListener(
          'mousedown',
          handleClickOutside(wrapperRef, closeFunc)
        );
      };
    }
  }, [wrapperRef]);

  return (
    <div>
      <div className={s.modal_bg}></div>
      <div
        ref={wrapperRef}
        className={`${s.modal__wrapper} ${otherClassForWrapper} ${
          position ? s.disableCenterPosition : ''
        }`}
        style={
          position && {
            left: `${left}px`,
            top: `${actualTop}px`,
          }
        }
      >
        {closeFunc && (
          <div className={s.modal_close} onClick={closeFunc}>
            <CloseSvg />
          </div>
        )}

        <div className={s.modal_content}>{children}</div>
      </div>
    </div>
  );
};
