import { useEffect, useRef, useState } from 'react';
import { ChevronLeft, ChevronRight, Pause, Play } from 'lucide-react';
import { listDirectory, getWebDAVBaseUrl, type EntryInfo } from '../webdav';
import { IMAGE_EXTS } from './MediaEntry';

interface Props {
  path: string;
}

export default function DirectorySlideshow({ path }: Props) {
  const [images, setImages]   = useState<EntryInfo[]>([]);
  const [idx, setIdx]         = useState(0);
  const [paused, setPaused]   = useState(() => localStorage.getItem('slideshow.paused') === '1');
  const [touched, setTouched] = useState(false);
  const touchTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);

  useEffect(() => {
    if (!path) { setImages([]); return; }
    listDirectory(path)
      .then(entries => {
        const imgs = entries.filter(e => {
          if (e.type !== 'file') return false;
          const ext = e.name.split('.').pop()?.toLowerCase() ?? '';
          return IMAGE_EXTS.has(ext);
        });
        setImages(imgs);
        const saved = parseInt(localStorage.getItem(`slideshow.idx:${path}`) ?? '0', 10);
        setIdx(imgs.length > 0 ? Math.min(saved, imgs.length - 1) : 0);
      })
      .catch(() => setImages([]));
  }, [path]);

  useEffect(() => {
    if (images.length <= 1 || paused) return;
    const t = setInterval(() => setIdx(i => (i + 1) % images.length), 4000);
    return () => clearInterval(t);
  }, [images.length, paused]);

  useEffect(() => {
    if (images.length === 0) return;
    localStorage.setItem(`slideshow.idx:${path}`, String(idx));
  }, [idx, path, images.length]);

  useEffect(() => () => clearTimeout(touchTimer.current), []);

  if (images.length === 0) return null;

  const current = images[idx];
  const prev = () => setIdx(i => (i - 1 + images.length) % images.length);
  const next = () => setIdx(i => (i + 1) % images.length);

  const handleTouch = () => {
    setTouched(true);
    clearTimeout(touchTimer.current);
    touchTimer.current = setTimeout(() => setTouched(false), 3000);
  };

  const controlsVisible = touched ? 'opacity-100' : 'opacity-0 group-hover:opacity-100';

  return (
    <div className="mb-3 rounded-lg overflow-hidden">
      <div className="relative group h-48" onPointerDown={handleTouch}>
        <img
          key={current.path}
          src={getWebDAVBaseUrl() + current.path}
          alt={current.name}
          className="w-full h-full object-contain"
        />

        {images.length > 1 && (
          <>
            {/* Prev / next */}
            <div className={`absolute inset-0 flex items-center justify-between px-2 pointer-events-none transition-opacity duration-200 ${controlsVisible}`}>
              <button onClick={prev} className="pointer-events-auto p-1 rounded-full bg-black/50 text-white hover:bg-black/70">
                <ChevronLeft className="w-5 h-5" />
              </button>
              <button onClick={next} className="pointer-events-auto p-1 rounded-full bg-black/50 text-white hover:bg-black/70">
                <ChevronRight className="w-5 h-5" />
              </button>
            </div>

            {/* Pause / play — centered */}
            <div className={`absolute inset-0 flex items-center justify-center pointer-events-none transition-opacity duration-200 ${controlsVisible}`}>
              <button
                onClick={() => setPaused(p => { const next = !p; localStorage.setItem('slideshow.paused', next ? '1' : '0'); return next; })}
                className="pointer-events-auto p-3 rounded-full bg-black/50 text-white hover:bg-black/70"
              >
                {paused ? <Play className="w-7 h-7" /> : <Pause className="w-7 h-7" />}
              </button>
            </div>

            {/* Dots */}
            <div className={`absolute bottom-0 left-0 right-0 flex justify-center gap-1.5 py-1.5 transition-opacity duration-200 ${controlsVisible}`}>
              {images.map((_, i) => (
                <button
                  key={i}
                  onClick={() => setIdx(i)}
                  className={`w-1.5 h-1.5 rounded-full transition-colors ${i === idx ? 'bg-white' : 'bg-white/40'}`}
                />
              ))}
            </div>
          </>
        )}
      </div>
    </div>
  );
}
