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

interface ImageModalProps {
  imageUrl?: string;
  images?: string[];
  currentIndex?: number;
  onClose?: () => void;
}

export const ImageModal: React.FC<ImageModalProps> = ({
  imageUrl,
  images,
  currentIndex = 0,
  onClose,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [imageSrc, setImageSrc] = useState("");
  const [currentImgIndex, setCurrentImgIndex] = useState(0);

  // Если передан imageUrl через props, используем props-режим
  const isPropsMode = imageUrl !== undefined;

  useEffect(() => {
    if (isPropsMode) {
      // Режим с props
      if (imageUrl) {
        setImageSrc(imageUrl);
        setIsOpen(true);
        setCurrentImgIndex(currentIndex || 0);
      } else {
        setIsOpen(false);
      }
    } else {
      // Режим с event listeners (обратная совместимость)
      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);
      };
    }
  }, [isPropsMode, imageUrl, currentIndex]);

  const handleClose = useCallback(() => {
    setIsOpen(false);
    if (onClose) {
      onClose();
    }
  }, [onClose]);

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

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

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

  const handleNext = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (images && images.length > 0) {
      const nextIndex = (currentImgIndex + 1) % images.length;
      setCurrentImgIndex(nextIndex);
      setImageSrc(images[nextIndex]);
    }
  };

  const handlePrev = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (images && images.length > 0) {
      const prevIndex = (currentImgIndex - 1 + images.length) % images.length;
      setCurrentImgIndex(prevIndex);
      setImageSrc(images[prevIndex]);
    }
  };

  if (!isOpen) return null;

  const showNavigation = isPropsMode && images && images.length > 1;

  return (
    <div
      id="imageModal"
      className="image-modal"
      style={{ display: "block" }}
      onClick={handleBackdropClick}
    >
      <span className="image-modal-close" onClick={handleClose}>
        &times;
      </span>
      {showNavigation && (
        <>
          <button
            className="image-modal-nav image-modal-nav-prev"
            onClick={handlePrev}
            style={{
              position: "absolute",
              left: "20px",
              top: "50%",
              transform: "translateY(-50%)",
              background: "rgba(0, 0, 0, 0.5)",
              color: "white",
              border: "none",
              borderRadius: "50%",
              width: "50px",
              height: "50px",
              cursor: "pointer",
              fontSize: "24px",
              zIndex: 1001,
            }}
          >
            ‹
          </button>
          <button
            className="image-modal-nav image-modal-nav-next"
            onClick={handleNext}
            style={{
              position: "absolute",
              right: "20px",
              top: "50%",
              transform: "translateY(-50%)",
              background: "rgba(0, 0, 0, 0.5)",
              color: "white",
              border: "none",
              borderRadius: "50%",
              width: "50px",
              height: "50px",
              cursor: "pointer",
              fontSize: "24px",
              zIndex: 1001,
            }}
          >
            ›
          </button>
        </>
      )}
      <img
        className="image-modal-content"
        id="modalImage"
        src={imageSrc}
        alt="Preview"
      />
    </div>
  );
};
