"use client";

import React, { useEffect, useCallback, useState } from "react";
import { createPortal } from "react-dom";
import Image from "next/image";
import { X, ChevronLeft, ChevronRight, Mountain as MountainIcon } from "lucide-react";
import type { GalleryImage } from "@/types/gallery";
import styles from "./GalleryLightbox.module.css";

interface GalleryLightboxProps {
  images: GalleryImage[];
  currentIndex: number;
  mountainName: string;
  onClose: () => void;
  onNavigate: (index: number) => void;
}

export default function GalleryLightbox({
  images,
  currentIndex,
  mountainName,
  onClose,
  onNavigate,
}: GalleryLightboxProps) {
  const currentImage = images[currentIndex];
  const total = images.length;
  const hasMultiple = total > 1;

  const handlePrev = useCallback(() => {
    if (!hasMultiple) return;
    const nextIdx = (currentIndex - 1 + total) % total;
    onNavigate(nextIdx);
  }, [currentIndex, hasMultiple, onNavigate, total]);

  const handleNext = useCallback(() => {
    if (!hasMultiple) return;
    const nextIdx = (currentIndex + 1) % total;
    onNavigate(nextIdx);
  }, [currentIndex, hasMultiple, onNavigate, total]);

  // Keyboard navigation & lock body scroll
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
      } else if (e.key === "ArrowLeft") {
        handlePrev();
      } else if (e.key === "ArrowRight") {
        handleNext();
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      document.body.style.overflow = originalOverflow;
    };
  }, [handleNext, handlePrev, onClose]);

  // Simple touch swipe for mobile
  const [touchStartX, setTouchStartX] = useState<number | null>(null);

  const handleTouchStart = (e: React.TouchEvent) => {
    setTouchStartX(e.touches[0].clientX);
  };

  const handleTouchEnd = (e: React.TouchEvent) => {
    if (touchStartX === null) return;
    const touchEndX = e.changedTouches[0].clientX;
    const diff = touchStartX - touchEndX;

    if (Math.abs(diff) > 45) {
      if (diff > 0) {
        handleNext();
      } else {
        handlePrev();
      }
    }
    setTouchStartX(null);
  };

  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted || !currentImage) return null;

  return createPortal(
    <div
      className={styles.backdrop}
      role="dialog"
      aria-modal="true"
      aria-label={`Galeri foto ${mountainName}`}
      onClick={onClose}
    >
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        onTouchStart={handleTouchStart}
        onTouchEnd={handleTouchEnd}
      >
        {/* ── Top Bar: Mountain Info & Close Button ────────────── */}
        <div className={styles.topBar}>
          <div className={styles.topInfo}>
            <span className={styles.mountainBadge}>
              <MountainIcon size={14} aria-hidden="true" />
              <span>{mountainName}</span>
            </span>
            {hasMultiple && (
              <span className={styles.counter}>
                {currentIndex + 1} / {total}
              </span>
            )}
          </div>

          <button
            type="button"
            className={styles.closeBtn}
            onClick={onClose}
            aria-label="Tutup pratinjau foto"
          >
            <X size={20} />
          </button>
        </div>

        {/* ── Main Photo Container with Navigation Arrows ─────── */}
        <div className={styles.mainStage}>
          {hasMultiple && (
            <button
              type="button"
              className={`${styles.navBtn} ${styles.navBtnPrev}`}
              onClick={handlePrev}
              aria-label="Foto sebelumnya"
            >
              <ChevronLeft size={24} />
            </button>
          )}

          <div className={styles.imageContainer}>
            <Image
              src={currentImage.image_url}
              alt={currentImage.caption || mountainName}
              fill
              unoptimized
              priority
              quality={95}
              sizes="(max-width: 1024px) 95vw, 1100px"
              className={styles.fullImage}
            />
          </div>

          {hasMultiple && (
            <button
              type="button"
              className={`${styles.navBtn} ${styles.navBtnNext}`}
              onClick={handleNext}
              aria-label="Foto selanjutnya"
            >
              <ChevronRight size={24} />
            </button>
          )}
        </div>

        {/* ── Bottom Caption ──────────────────────────────────── */}
        {currentImage.caption && (
          <div className={styles.captionBox}>
            <p className={styles.captionText}>{currentImage.caption}</p>
          </div>
        )}
      </div>
    </div>,
    document.body
  );
}
