'use client';

import s from './modal-content.module.scss';
import { MouseEvent, ReactNode, useRef } from 'react';
import clsx from 'clsx';
import { useModal } from '@core/providers/modal-provider';
import { detectIOS, useClickOutside } from '@shared/lib';
import { CloseIcon } from '@shared/ui/modal/close-icon';

function ModalContent(props: {
  children: ReactNode;
  className?: string;
  innerClassName?: string;
  closeByClickOutside?: boolean;
}) {
  const {
    children,
    className,
    innerClassName,
    closeByClickOutside = false,
  } = props;

  const modal = useModal();

  const hideModal = () => modal.hideModal();

  const modalRef = useRef<HTMLDivElement | null>(null);

  const handleClickOutside = () => closeByClickOutside && hideModal();

  useClickOutside(modalRef, handleClickOutside);

  const isIOS = detectIOS();

  const disableClick = (e: MouseEvent<HTMLDivElement>) => e.stopPropagation();

  return (
    <div
      className={clsx(className, s.ModalContent, isIOS && s.ModalContent_isIOS)}
      ref={modalRef}
      onClick={disableClick}
    >
      <CloseIcon className={s.CloseBtn} onClick={hideModal} />
      <div className={clsx(s.Inner, innerClassName)}>{children}</div>
    </div>
  );
}

export { ModalContent };
