import { ReactNode } from 'react';
import clsx from 'clsx';
import IconX from './Icon/IconX';

type ModalProps = {
  open: boolean;
  onClose: () => void;

  title?: string;
  icon?: ReactNode;

  children: ReactNode; // body content

  footer?: ReactNode; // buttons

  width?: 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '4xl' | '5xl' | '6xl';
};

const widthMap = {
  sm: 'max-w-sm',
  md: 'max-w-md',
  lg: 'max-w-lg',
  xl: 'max-w-xl',
  '2xl': 'max-w-2xl',
  '4xl': 'max-w-4xl',
  '5xl': 'max-w-5xl',
  '6xl': 'max-w-6xl',
};

const Modal = ({
  open,
  onClose,
  title,
  icon,
  children,
  footer,
  width = 'lg',
}: ModalProps) => {
  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* BACKDROP */}
      <div
        className="absolute inset-0 bg-black/40"
        onClick={onClose}
      />

      {/* MODAL */}
      <div
        className={clsx(
          'relative z-10 w-full mx-4 rounded-xl bg-white shadow-xl flex flex-col',
          'max-h-[90vh]', // 👈 prevents overflow outside screen
          widthMap[width]
        )}
      >
        {/* HEADER (fixed) */}
        <div className="flex items-center justify-between border-b px-4 py-3">
          <div className="flex items-center gap-2">
            {icon && <span className="text-lg">{icon}</span>}
            {title && (
              <h2 className="text-sm font-semibold text-slate-800">
                {title}
              </h2>
            )}
          </div>

          {/* CLOSE */}
          <button
            onClick={onClose}
            className="text-slate-400 hover:text-slate-700 text-lg"
          >
            <IconX />
          </button>
        </div>

        {/* BODY (scrollable) */}
        <div className="flex-1 overflow-y-auto px-4 py-3">
          {children}
        </div>

        {/* FOOTER (fixed) */}
        {footer && (
          <div className="border-t px-4 py-3 flex justify-end gap-2">
            {footer}
          </div>
        )}
      </div>
    </div>
  );
};

export default Modal;