'use client';

import { useState, useEffect, useCallback } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { db } from '@/lib/firebase';
import { collection, query, where, onSnapshot } from 'firebase/firestore';
import { ChevronLeft, ChevronRight, X, Pause, Play } from 'lucide-react';

export default function SlideshowClient() {
  const router = useRouter();
  const params = useParams();
  const eventId = params.id as string;
  const [photos, setPhotos] = useState<any[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [playing, setPlaying] = useState(true);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!eventId) return;
    const q = query(
      collection(db, 'events', eventId, 'photos'),
      where('isApproved', '==', true)
    );
    const unsub = onSnapshot(q, (snap) => {
      const items = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
      setPhotos(items);
      setLoading(false);
    });
    return () => unsub();
  }, [eventId]);

  const next = useCallback(() => {
    setCurrentIndex((prev) => (prev + 1) % Math.max(1, photos.length));
  }, [photos.length]);

  const prev = useCallback(() => {
    setCurrentIndex((prev) => (prev - 1 + Math.max(1, photos.length)) % Math.max(1, photos.length));
  }, [photos.length]);

  useEffect(() => {
    if (!playing || photos.length === 0) return;
    const timer = setInterval(next, 4000);
    return () => clearInterval(timer);
  }, [playing, photos.length, next]);

  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === 'ArrowRight') next();
      if (e.key === 'ArrowLeft') prev();
      if (e.key === ' ') setPlaying((p) => !p);
      if (e.key === 'Escape') router.push(`/event/${eventId}`);
    };
    window.addEventListener('keydown', handleKey);
    return () => window.removeEventListener('keydown', handleKey);
  }, [next, prev, router, eventId]);

  if (loading) {
    return (
      <div className="fixed inset-0 bg-black flex items-center justify-center">
        <div className="h-8 w-8 border-2 border-white border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  if (photos.length === 0) {
    return (
      <div className="fixed inset-0 bg-black flex items-center justify-center text-white">
        <div className="text-center">
          <p className="text-xl mb-4">No approved photos yet</p>
          <button onClick={() => router.push(`/event/${eventId}`)} className="h-10 px-4 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white hover:from-indigo-600 hover:to-purple-700 transition-all">
            Back to Event
          </button>
        </div>
      </div>
    );
  }

  const photo = photos[currentIndex];

  return (
    <div className="fixed inset-0 bg-black flex items-center justify-center select-none">
      <img
        src={photo.url}
        alt=""
        className="max-w-full max-h-full object-contain transition-opacity duration-700"
        onClick={next}
      />

      {/* Info overlay */}
      <div className="absolute bottom-0 left-0 right-0 p-6 bg-gradient-to-t from-black/70 to-transparent">
        <p className="text-white text-lg font-medium">{photo.guestName || 'Guest'}</p>
        <p className="text-white/60 text-sm">
          {currentIndex + 1} / {photos.length}
        </p>
      </div>

      {/* Controls */}
      <button
        onClick={() => router.push(`/event/${eventId}`)}
        className="absolute top-4 left-4 h-10 w-10 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/30 transition-colors"
        aria-label="Close slideshow"
      >
        <X className="h-5 w-5" />
      </button>

      <button
        onClick={prev}
        className="absolute left-4 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/30 transition-colors"
        aria-label="Previous photo"
      >
        <ChevronLeft className="h-6 w-6" />
      </button>

      <button
        onClick={next}
        className="absolute right-4 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/30 transition-colors"
        aria-label="Next photo"
      >
        <ChevronRight className="h-6 w-6" />
      </button>

      <button
        onClick={() => setPlaying((p) => !p)}
        className="absolute top-4 right-4 h-10 w-10 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/30 transition-colors"
        aria-label={playing ? 'Pause slideshow' : 'Play slideshow'}
      >
        {playing ? <Pause className="h-5 w-5" /> : <Play className="h-5 w-5" />}
      </button>

      {/* Progress bar */}
      <div className="absolute bottom-0 left-0 right-0 h-1 bg-white/10">
        <div
          className="h-full bg-white/60 transition-all duration-300"
          style={{ width: `${((currentIndex + 1) / photos.length) * 100}%` }}
        />
      </div>
    </div>
  );
}
