'use client';

import React, { useEffect, useRef } from 'react';

import { IoClose } from 'react-icons/io5';

import { cn } from '@/lib/utils';

interface ModalActionButton {
  icon: React.ReactNode;
  onClick: () => void;
  ariaLabel?: string;
  title?: string;
}

interface ModalProps {
  children: React.ReactNode;
  onClose: () => void;
  isOpen: boolean;
  title?: string;
  subtitle?: string;
  actionButton?: ModalActionButton;
  disableOutsideClick?: boolean;
  disableEscape?: boolean;
  className?: string;
  overlayClassName?: string;
  contentRef?: React.RefObject<HTMLDivElement>;
}

const Modal: React.FC<ModalProps> = ({
  children,
  onClose,
  isOpen,
  title,
  subtitle,
  actionButton,
  disableOutsideClick = false,
  disableEscape = false,
  className = '',
  overlayClassName = '',
  contentRef,
}) => {
  const internalRef = useRef<HTMLDivElement>(null);
  const modalContentRef = contentRef || internalRef;

  useEffect(() => {
    if (!isOpen) return;

    // Lock body scroll
    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    // Handle escape key
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !disableEscape) {
        onClose();
      }
    };

    window.addEventListener('keydown', handleKeyDown);

    return () => {
      document.body.style.overflow = originalOverflow;
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen, onClose, disableEscape]);

  // Handle click outside
  const handleOverlayClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (
      !disableOutsideClick &&
      modalContentRef.current &&
      e.target instanceof Node &&
      !modalContentRef.current.contains(e.target)
    ) {
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div
      className={cn(
        'fixed inset-0 z-[1000] flex items-center justify-center bg-black/80 backdrop-blur-md',
        overlayClassName
      )}
      onClick={handleOverlayClick}
      role="dialog"
      aria-modal="true"
    >
      <div
        ref={modalContentRef}
        className={cn('flex flex-col max-h-[95vh] max-w-[90vw] bg-white shadow-2xl', className)}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Sticky Header - only if title or subtitle provided */}
        {(title || subtitle) && (
          <div className="sticky top-0 z-10 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between flex-shrink-0">
            <div className="flex flex-col">
              {title && <h2 className="text-base lg:text-xl font-bold text-mma-blue">{title}</h2>}
              {subtitle && (
                <p className="text-sm lg:text-base text-gray-600 font-semibold mt-1">{subtitle}</p>
              )}
            </div>
            <div className="flex items-center gap-3 lg:gap-5 flex-shrink-0">
              {actionButton && (
                <button
                  onClick={actionButton.onClick}
                  className="text-mma-blue hover:text-mma-yellow transition-colors"
                  aria-label={actionButton.ariaLabel}
                  title={actionButton.title}
                >
                  {actionButton.icon}
                </button>
              )}
              <button
                onClick={onClose}
                className="text-mma-blue hover:text-mma-yellow transition"
                aria-label="Bezárás"
              >
                <IoClose size={30} />
              </button>
            </div>
          </div>
        )}

        {/* Content */}
        <div className="flex-1 overflow-y-auto">{children}</div>
      </div>
    </div>
  );
};

export default Modal;
