import { useEffect } from 'react';
import { Cancel } from '../icons/icons';

export default function Modal({
  open,
  title,
  children,
  onClose,
  actions,
  size = 'medium',
  customSize = null,
}) {
  useEffect(() => {
    if (open) {
      const tableContainer = document.querySelector('.MuiTableContainer-root');
      if (tableContainer) {
        tableContainer.style.overflow = 'hidden';
        return () => {
          tableContainer.style.overflow = 'auto';
        };
      }
    }
  }, [open]);

  if (!open) return null;

  const getSizeClass = () => {
    switch (size) {
      case 'small':
        return 'w-[20rem]'; // 320px
      case 'medium':
        return 'w-[31.25rem]';
      case 'large':
        return 'w-[90vw] md:w-[62.5rem] max-w-[62.5rem]'; // 1000px max
      case 'xlarge':
        return 'w-[90vw] md:w-[75rem] max-w-[75rem]'; // 1200px max
      default:
        return 'w-[90vw] md:w-[31.25rem] max-w-[31.25rem]';
    }
  };

  const modalStyle = customSize ? { width: `${customSize}rem` } : {};

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center width-max-content">
      <div className="absolute inset-0 bg-black/30" onClick={onClose}></div>
      <div
        className={`relative bg-base-100 rounded-xl shadow-lg max-w-[90vw] mx-4 p-6 ${!customSize ? getSizeClass() : ''}`}
        style={modalStyle}
      >
        <div className="flex justify-between items-start">
          <div className="text-lg font-semibold mb-4">{title}</div>
          <Cancel onClick={onClose} className="cursor-pointer" />
        </div>
        <div className="mb-4">{children}</div>
        <div className="flex justify-end gap-2">{actions}</div>
      </div>
    </div>
  );
}
