import { useEffect, useRef, useState } from "react";
import { useBackLayer } from "../../app/useBackLayer.js";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { CloseIcon, ForwardIcon, PreviousIcon } from "../../shared/ActionIcons.jsx";
import { galleryIndexAfterSwipe, isGallerySwipe, moveGalleryIndex } from "./image-gallery.js";

export function ImageGallery({ images, initialIndex, onClose }) {
  const { t } = useI18n();
  const [index, setIndex] = useState(() => moveGalleryIndex(initialIndex, 0, images.length));
  const [failed, setFailed] = useState(false);
  const pointerStart = useRef(null);
  const swiped = useRef(false);
  const dismiss = useBackLayer(true, onClose, "image-gallery", { preferTop: true });
  const image = images[index];

  useEffect(() => {
    setFailed(false);
  }, [index]);

  useEffect(() => {
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKeyDown = (event) => {
      if (event.key === "Escape") dismiss();
      if (event.key === "ArrowLeft") setIndex((current) => moveGalleryIndex(current, -1, images.length));
      if (event.key === "ArrowRight") setIndex((current) => moveGalleryIndex(current, 1, images.length));
    };
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.body.style.overflow = previousOverflow;
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [dismiss, images.length]);

  function move(delta) {
    setIndex((current) => moveGalleryIndex(current, delta, images.length));
  }

  function finishSwipe(event) {
    if (pointerStart.current == null) return;
    swiped.current = isGallerySwipe(pointerStart.current, event.clientX);
    setIndex((current) => galleryIndexAfterSwipe(current, pointerStart.current, event.clientX, images.length));
    pointerStart.current = null;
  }

  return <div className="image-gallery-overlay" role="dialog" aria-modal="true" aria-label={t("gallery.title")} onClick={(event) => { if (event.target === event.currentTarget) dismiss(); }}>
    <button type="button" className="image-gallery-close" aria-label={t("gallery.close")} onClick={() => dismiss()}><CloseIcon /></button>
    <div className="image-gallery-stage" onClick={(event) => { if (event.target === event.currentTarget && !swiped.current) dismiss(); swiped.current = false; }} onPointerDown={(event) => { pointerStart.current = event.clientX; swiped.current = false; }} onPointerUp={finishSwipe} onPointerCancel={() => { pointerStart.current = null; swiped.current = false; }}>
      {failed
        ? <p className="image-gallery-error">{t("gallery.loadFailed")}</p>
        : <img className="image-gallery-image" src={image.previewUrl} alt={image.name || t("conversation.attachedImage")} onError={() => setFailed(true)} />}
    </div>
    {images.length > 1 && <>
      <button type="button" className="image-gallery-nav image-gallery-previous" disabled={index === 0} aria-label={t("gallery.previous")} onClick={() => move(-1)}><PreviousIcon /></button>
      <button type="button" className="image-gallery-nav image-gallery-next" disabled={index === images.length - 1} aria-label={t("gallery.next")} onClick={() => move(1)}><ForwardIcon /></button>
      <div className="image-gallery-count" aria-live="polite">{index + 1} / {images.length}</div>
    </>}
  </div>;
}
