import { useEffect, useRef, type ReactNode, type HTMLAttributes, type ReactElement } from "react";

export interface ModalProps extends HTMLAttributes<HTMLDivElement> {
  isOpen: boolean;
  onClose: () => void;
  title?: string;
  footer?: ReactNode;
  closeOnOverlayClick?: boolean;
  closeOnEscape?: boolean;
  size?: "sm" | "md" | "lg" | "xl" | "full";
}

export function Modal({
  isOpen,
  onClose,
  title,
  footer,
  closeOnOverlayClick = true,
  closeOnEscape = true,
  size = "md",
  children,
  className = "",
  ...props
}: ModalProps): ReactElement | null {
  const dialogRef = useRef<HTMLDivElement>(null);
  const modalId = useRef(`modal-${Math.random().toString(36).substring(2, 11)}`);

  type ModalSize = "sm" | "md" | "lg" | "xl" | "full";
  const sizeStyles: Record<ModalSize, string> = {
    sm: "max-w-md",
    md: "max-w-lg",
    lg: "max-w-2xl",
    xl: "max-w-4xl",
    full: "max-w-full mx-4",
  };

  useEffect(() => {
    const handleEscape = (event: KeyboardEvent): void => {
      if (closeOnEscape && event.key === "Escape" && isOpen) {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener("keydown", handleEscape);
      document.body.style.overflow = "hidden";
      // Focus the modal when opened
      dialogRef.current?.focus();
    }

    return (): void => {
      document.removeEventListener("keydown", handleEscape);
      document.body.style.overflow = "";
    };
  }, [isOpen, closeOnEscape, onClose]);

  if (!isOpen) {
    return null;
  }

  const handleOverlayClick = (event: React.MouseEvent<HTMLDivElement>): void => {
    if (closeOnOverlayClick && event.target === event.currentTarget) {
      onClose();
    }
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      style={{ background: "rgba(0,0,0,0.5)" }}
      onClick={handleOverlayClick}
      role="dialog"
      aria-modal="true"
      aria-labelledby={title ? `${modalId.current}-title` : undefined}
      {...props}
    >
      <div
        ref={dialogRef}
        tabIndex={-1}
        className={`rounded-lg w-full ${sizeStyles[size]} ${className}`}
        style={{
          background: "var(--surface)",
          border: "1px solid var(--border)",
        }}
        role="document"
      >
        {title && (
          <div
            className="px-6 py-4 flex items-center justify-between"
            style={{ borderBottom: "1px solid var(--border)" }}
          >
            <h2
              id={`${modalId.current}-title`}
              className="text-lg font-semibold"
              style={{ color: "var(--text)" }}
            >
              {title}
            </h2>
            <button
              type="button"
              onClick={onClose}
              className="transition-colors p-1 rounded"
              style={{ color: "var(--muted)" }}
              aria-label="Close modal"
            >
              <svg
                className="w-6 h-6"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                aria-hidden="true"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
          </div>
        )}
        <div className="px-6 py-4 max-h-[70vh] overflow-y-auto">{children}</div>
        {footer && (
          <div
            className="px-6 py-4 rounded-b-lg flex justify-end gap-2"
            style={{
              borderTop: "1px solid var(--border)",
              background: "var(--bg-mid)",
            }}
          >
            {footer}
          </div>
        )}
      </div>
    </div>
  );
}
