/**
 * Modal Component - ProRank SEO
 *
 * Premium modal dialog component with backdrop and focus trap.
 * Supports different sizes and variants.
 *
 * @example
 * <Modal
 *   isOpen={isOpen}
 *   onClose={handleClose}
 *   title="Confirm Action"
 *   footer={
 *     <>
 *       <Button variant="secondary" onClick={handleClose}>Cancel</Button>
 *       <Button variant="primary" onClick={handleConfirm}>Confirm</Button>
 *     </>
 *   }
 * >
 *   Are you sure you want to continue?
 * </Modal>
 */

import React, { useEffect } from 'react';
import { createPortal } from 'react-dom';
import clsx from 'clsx';
import { XMarkIcon } from '@heroicons/react/24/outline';

const Modal = ({
  isOpen,
  onClose,
  onRequestClose,
  title,
  children,
  footer,
  size = 'md',
  closeButton = true,
  closeOnBackdrop = true,
  closeOnEsc = true,
  className = '',
  contentClassName = '',
  ...props
}) => {
  const resolvedIsOpen = typeof isOpen === 'boolean' ? isOpen : true;
  const resolvedOnClose = onClose || onRequestClose;

  // Handle ESC key press
  useEffect(() => {
    if (!resolvedIsOpen || !closeOnEsc || !resolvedOnClose) return;

    const handleEscape = (e) => {
      if (e.key === 'Escape') {
        resolvedOnClose();
      }
    };

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [resolvedIsOpen, closeOnEsc, resolvedOnClose]);

  // Handle body scroll lock
  useEffect(() => {
    if (resolvedIsOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }

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

  if (!resolvedIsOpen) return null;

  // Size variants
  const sizeStyles = {
    sm: 'pr:max-w-md',
    md: 'pr:max-w-lg',
    lg: 'pr:max-w-2xl',
    xl: 'pr:max-w-4xl',
    full: 'pr:max-w-7xl',
  };

  // Modal content
  const modalContent = (
    <div
      className="pr:fixed pr:inset-0 pr:z-modal-backdrop pr:flex pr:items-center pr:justify-center pr:p-4"
      onClick={closeOnBackdrop && resolvedOnClose ? resolvedOnClose : undefined}
    >
      {/* Backdrop */}
      <div className="pr:fixed pr:inset-0 pr:bg-black/50 pr:transition-opacity" />

      {/* Modal */}
      <div
        className={clsx(
          'pr:relative',
          'pr:bg-white',
          'pr:rounded-lg',
          'pr:shadow-modal',
          'pr:w-full',
          'pr:max-h-[90vh]',
          'pr:flex',
          'pr:flex-col',
          'pr:animate-scale-in',
          sizeStyles[size],
          className
        )}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby={title ? 'modal-title' : undefined}
        {...props}
      >
        {/* Header */}
        {(title || closeButton) && (
          <div className="pr:flex pr:items-center pr:justify-between pr:px-6 pr:py-4 pr:border-b pr:border-gray-200">
            {title && (
              <h2
                id="modal-title"
                className="pr:text-xl pr:font-semibold pr:text-gray-900"
              >
                {title}
              </h2>
            )}

            {closeButton && (
              <button
                type="button"
                onClick={resolvedOnClose}
                className="pr:text-gray-400 pr:hover:text-gray-600 pr:transition-colors pr:focus:outline-hidden pr:focus:ring-2 pr:focus:ring-primary-500 pr:rounded-md pr:p-1"
                aria-label="Close modal"
              >
                <XMarkIcon className="pr:w-6 pr:h-6" />
              </button>
            )}
          </div>
        )}

        {/* Content */}
        <div
          className={clsx(
            'pr:flex-1',
            'pr:px-6',
            'pr:py-4',
            'pr:overflow-y-auto',
            contentClassName
          )}
        >
          {children}
        </div>

        {/* Footer */}
        {footer && (
          <div className="pr:flex pr:items-center pr:justify-end pr:gap-3 pr:px-6 pr:py-4 pr:border-t pr:border-gray-200 pr:bg-gray-50">
            {footer}
          </div>
        )}
      </div>
    </div>
  );

  // Render in portal
  return createPortal(modalContent, document.body);
};

Modal.displayName = 'Modal';

export default Modal;
