import { useEffect } from "react";
import { X } from "lucide-react";

interface ImagePreviewModalProps {
  src: string | null;
  alt?: string;
  title?: string;
  onClose: () => void;
}

export function ImagePreviewModal({ src, alt, title, onClose }: ImagePreviewModalProps) {
  useEffect(() => {
    if (!src) return;

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        onClose();
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [onClose, src]);

  if (!src) return null;

  return (
    <div
      className="fixed inset-0 z-[80] flex items-center justify-center bg-black/75 p-5 backdrop-blur-sm"
      role="dialog"
      aria-modal="true"
      aria-label={title ?? alt ?? "Image preview"}
      onClick={onClose}
    >
      <div className="relative flex max-h-[92vh] max-w-[94vw] flex-col items-center" onClick={(event) => event.stopPropagation()}>
        <button
          type="button"
          onClick={onClose}
          className="absolute -right-3 -top-3 z-10 rounded-full bg-white p-2 text-slate-900 shadow-lg transition-colors hover:bg-slate-100"
          aria-label="Close preview"
        >
          <X className="h-5 w-5" />
        </button>
        {title && (
          <div className="mb-3 max-w-[84vw] rounded-full bg-black/45 px-4 py-1.5 text-sm font-medium text-white shadow-sm">
            {title}
          </div>
        )}
        <img
          src={src}
          alt={alt ?? title ?? "Image preview"}
          className="max-h-[84vh] max-w-[94vw] rounded-xl object-contain shadow-2xl"
        />
      </div>
    </div>
  );
}
