'use client';

import { ReactPortal } from './react-portal';
import { Icon } from './icon';
import { twMerge } from 'tailwind-merge';
import { useEffect } from 'react';
import { ModalProps } from '../types';

export const Modal = (props: ModalProps) => {
  const {
    children,
    portalId,
    open,
    setOpen,
    title = '',
    showCloseButton = true,
    className,
    overlayClassName,
    headerWrapperClassName,
    titleClassName,
    closeButtonClassName,
    iconName = 'close',
    iconSize = 16,
    iconClassName
  } = props;

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : 'auto';

    return () => {
      document.body.style.overflow = 'auto';
    };
  }, [open]);

  if (!open) return null;

  return (
    <ReactPortal wrapperId={portalId}>
      <div
        className={twMerge(
          'fixed top-0 left-0 w-screen h-screen bg-primary bg-opacity-60 z-50',
          overlayClassName
        )}
      />
      <section
        className={twMerge(
          'fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-50 bg-white',
          className
        )}
      >
        {(showCloseButton || title) && (
          <div
            className={twMerge(
              'flex px-6 py-4 border-b border-gray-400',
              headerWrapperClassName
            )}
          >
            {title && (
              <h3 className={twMerge('text-lg font-light', titleClassName)}>
                {title}
              </h3>
            )}
            {showCloseButton && (
              <button
                type="button"
                onClick={() => setOpen(false)}
                className={twMerge('ml-auto', closeButtonClassName)}
              >
                <Icon
                  name={iconName}
                  size={iconSize}
                  className={iconClassName}
                />
              </button>
            )}
          </div>
        )}
        {children}
      </section>
    </ReactPortal>
  );
};
