import React, { useEffect, useState } from "react";

export const ImageModal: React.FC = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [imageSrc, setImageSrc] = useState("");

  useEffect(() => {
    const handleImageClick = (e: Event) => {
      const target = e.target as HTMLElement;
      if (target.classList.contains("note-image")) {
        const src =
          target.getAttribute("src") || target.getAttribute("data-src");
        if (src) {
          setImageSrc(src);
          setIsOpen(true);
        }
      }
    };

    document.addEventListener("click", handleImageClick);

    return () => {
      document.removeEventListener("click", handleImageClick);
    };
  }, []);

  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape" && isOpen) {
        setIsOpen(false);
      }
    };

    document.addEventListener("keydown", handleEscape);
    return () => document.removeEventListener("keydown", handleEscape);
  }, [isOpen]);

  const handleClose = () => {
    setIsOpen(false);
  };

  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      handleClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div
      id="imageModal"
      className="image-modal"
      style={{ display: "block" }}
      onClick={handleBackdropClick}
    >
      <span className="image-modal-close" onClick={handleClose}>
        &times;
      </span>
      <img
        className="image-modal-content"
        id="modalImage"
        src={imageSrc}
        alt="Preview"
      />
    </div>
  );
};
