import { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { ChevronLeft, ChevronRight, X } from 'lucide-react';

interface ScreenshotCarouselProps {
  screenshots?: string[];
  placeholder?: string;
}

export default function ScreenshotCarousel({ screenshots }: ScreenshotCarouselProps) {
  const [active, setActive] = useState(0);
  const [preview, setPreview] = useState<number | null>(null);
  const scrollRef = useRef<HTMLDivElement>(null);

  const scrollTo = useCallback((i: number) => {
    setActive(i);
    scrollRef.current?.children[i]?.scrollIntoView({
      behavior: 'smooth',
      block: 'nearest',
      inline: 'center',
    });
  }, []);

  const prev = useCallback(() => {
    if (!screenshots) return;
    scrollTo(active > 0 ? active - 1 : screenshots.length - 1);
  }, [active, screenshots, scrollTo]);

  const next = useCallback(() => {
    if (!screenshots) return;
    scrollTo(active < screenshots.length - 1 ? active + 1 : 0);
  }, [active, screenshots, scrollTo]);

  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            const idx = Array.from(el.children).indexOf(e.target);
            if (idx >= 0) setActive(idx);
          }
        });
      },
      { root: el, threshold: 0.6 }
    );
    Array.from(el.children).forEach((c) => observer.observe(c));
    return () => observer.disconnect();
  }, []);

  // 同步 lightbox 切换到轮播
  useEffect(() => {
    if (preview === null) return;
    scrollTo(preview);
  }, [preview, scrollTo]);

  useEffect(() => {
    if (preview === null) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setPreview(null);
      if (e.key === 'ArrowLeft') setPreview((p) => p !== null ? (p > 0 ? p - 1 : screenshots!.length - 1) : null);
      if (e.key === 'ArrowRight') setPreview((p) => p !== null ? (p < screenshots!.length - 1 ? p + 1 : 0) : null);
    };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [preview, screenshots]);

  if (!screenshots || screenshots.length === 0) {
    return null;
  }

  return (
    <>
      <div className="screenshot-carousel">
        {screenshots.length > 1 && (
          <button className="screenshot-arrow screenshot-arrow-prev" onClick={prev} aria-label="Previous">
            <ChevronLeft size={18} />
          </button>
        )}
        <div className="screenshot-scroll" ref={scrollRef}>
          {screenshots.map((src, i) => (
            <div key={i} className="screenshot-slide" onClick={() => setPreview(i)}>
              <img src={src} alt={`Screenshot ${i + 1}`} className="screenshot-image" />
            </div>
          ))}
        </div>
        {screenshots.length > 1 && (
          <button className="screenshot-arrow screenshot-arrow-next" onClick={next} aria-label="Next">
            <ChevronRight size={18} />
          </button>
        )}
        {screenshots.length > 1 && (
          <div className="screenshot-dots">
            {screenshots.map((_, i) => (
              <button
                key={i}
                className={`screenshot-dot ${i === active ? 'active' : ''}`}
                onClick={() => scrollTo(i)}
              />
            ))}
          </div>
        )}
      </div>

      {preview !== null && createPortal(
        <div className="screenshot-lightbox" onClick={() => setPreview(null)}>
          <button className="screenshot-lightbox-close" onClick={() => setPreview(null)} aria-label="Close">
            <X size={24} />
          </button>
          {screenshots.length > 1 && (
            <button
              className="screenshot-lightbox-arrow screenshot-lightbox-prev"
              onClick={(e) => { e.stopPropagation(); setPreview(p => p !== null ? (p > 0 ? p - 1 : screenshots.length - 1) : null); }}
              aria-label="Previous"
            >
              <ChevronLeft size={28} />
            </button>
          )}
          <img
            src={screenshots[preview]}
            alt={`Screenshot ${preview + 1}`}
            className="screenshot-lightbox-img"
            onClick={(e) => e.stopPropagation()}
          />
          {screenshots.length > 1 && (
            <button
              className="screenshot-lightbox-arrow screenshot-lightbox-next"
              onClick={(e) => { e.stopPropagation(); setPreview(p => p !== null ? (p < screenshots.length - 1 ? p + 1 : 0) : null); }}
              aria-label="Next"
            >
              <ChevronRight size={28} />
            </button>
          )}
          <div className="screenshot-lightbox-counter">{preview + 1} / {screenshots.length}</div>
        </div>,
        document.body
      )}
    </>
  );
}
