import { useEffect, useRef } from 'react';
import './Modal.css';

interface ModalProps {
  open: boolean;
  onClose: () => void;
  title?: string;
  children: React.ReactNode;
  width?: string;
  centerTitle?: boolean;
  maxHeight?: string;
}

export default function Modal({
  open,
  onClose,
  title,
  children,
  width = '560px',
  centerTitle = false,
  maxHeight,
}: ModalProps) {
  const overlayRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [open]);

  if (!open) {
    return null;
  }

  return (
    <div
      className="modal-overlay"
      ref={overlayRef}
      onClick={e => {
        if (e.target === overlayRef.current) {
          onClose();
        }
      }}
    >
      <div
        className={`modal-container animate-slideUp ${!title ? 'modal-container--no-title' : ''}`}
        style={{
          width: '90%',
          maxWidth: width,
          position: 'relative',
          ...(maxHeight ? { maxHeight } : {}),
        }}
      >
        {title && (
          <div
            className="modal-header"
            style={centerTitle ? { justifyContent: 'center' } : undefined}
          >
            <h3
              className="modal-title"
              style={centerTitle ? { textAlign: 'center', flex: 1 } : undefined}
            >
              {title}
            </h3>
            <button
              className="modal-close"
              onClick={onClose}
              style={centerTitle ? { position: 'absolute', right: '16px' } : undefined}
            >
              <svg
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <line x1="18" y1="6" x2="6" y2="18" />
                <line x1="6" y1="6" x2="18" y2="18" />
              </svg>
            </button>
          </div>
        )}
        {!title && (
          <button
            className="modal-close modal-close--floating"
            onClick={onClose}
            style={{ position: 'absolute', top: '8px', right: '8px', zIndex: 1 }}
          >
            <svg
              width="20"
              height="20"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <line x1="18" y1="6" x2="6" y2="18" />
              <line x1="6" y1="6" x2="18" y2="18" />
            </svg>
          </button>
        )}
        <div className="modal-body" style={!title ? { paddingTop: 40 } : undefined}>{children}</div>
      </div>
    </div>
  );
}
