import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { ChevronLeft, ChevronRight, PlayCircle, Loader2 } from 'lucide-react';
import { YOUTUBE_CONFIG } from '../config';

// WARNING: The API key is hardcoded here as requested by the user.
// In a production environment, this should ideally be secured or restricted.
const YOUTUBE_API_KEY = YOUTUBE_CONFIG.API_KEY;
const CHANNEL_UPLOADS_PLAYLIST_ID = YOUTUBE_CONFIG.PLAYLIST_ID; // Playlist requested by user

interface Video {
  id: string;
  title: string;
  thumbnail: string;
}

export default function VideoGallery() {
  const [videos, setVideos] = useState<Video[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchVideos = async () => {
      // Manual Testimonials requested to be at the top
      const manualTestimonials = [
        { id: 'g35XLVb6jMI', title: 'Testimonial - Mr. Chetan & Mrs. Pallavi', thumbnail: 'https://img.youtube.com/vi/g35XLVb6jMI/mqdefault.jpg' },
        { id: 'k_2tznC-HCs', title: 'Testimonial - Mr. Pradip & Mrs. Ananya', thumbnail: 'https://img.youtube.com/vi/k_2tznC-HCs/mqdefault.jpg' },
        { id: 'TvDTbaB-9JY', title: 'Testimonial - Mr. Sagar & Mrs. Bharti', thumbnail: 'https://img.youtube.com/vi/TvDTbaB-9JY/mqdefault.jpg' },
        { id: 'wGIhuKVfnm8', title: 'Testimonial - Mr. Ram & Mrs. Mamta', thumbnail: 'https://img.youtube.com/vi/wGIhuKVfnm8/mqdefault.jpg' },
        { id: 'AHGReBLy1PQ', title: 'Testimonial - Mr. Harshad & Mrs. Trupti', thumbnail: 'https://img.youtube.com/vi/AHGReBLy1PQ/mqdefault.jpg' },
        { id: 'RKF6dERiAd4', title: 'Testimonial - Mr. Mitesh Sharma', thumbnail: 'https://img.youtube.com/vi/RKF6dERiAd4/mqdefault.jpg' },
      ];

      try {
        const response = await fetch(
          `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${CHANNEL_UPLOADS_PLAYLIST_ID}&maxResults=10&key=${YOUTUBE_API_KEY}`
        );
        const data = await response.json();
        
        if (data.items) {
          const fetchedVideos = data.items.map((item: any) => ({
            id: item.snippet.resourceId.videoId,
            title: item.snippet.title,
            thumbnail: item.snippet.thumbnails?.medium?.url || item.snippet.thumbnails?.default?.url,
          }));

          // Filter out any fetched videos that are already in the manual testimonials to prevent duplicates
          const filteredFetched = fetchedVideos.filter(
            (v: Video) => !manualTestimonials.some((t) => t.id === v.id)
          );

          // Get the single latest video for position 1
          const latestVideo = filteredFetched.length > 0 ? [filteredFetched[0]] : [];
          
          // Get the rest of the fetched videos
          const remainingFetched = filteredFetched.slice(1);

          // Interleave testimonials and remaining fetched videos starting from position 2
          const interleavedRemaining: Video[] = [];
          const maxLength = Math.max(manualTestimonials.length, remainingFetched.length);
          for (let i = 0; i < maxLength; i++) {
            if (i < manualTestimonials.length) interleavedRemaining.push(manualTestimonials[i]);
            if (i < remainingFetched.length) interleavedRemaining.push(remainingFetched[i]);
          }

          // Show latest video first, then the interleaved mix
          setVideos([...latestVideo, ...interleavedRemaining]);
        }
      } catch (error) {
        console.error('Error fetching YouTube videos:', error);
        // Fallback videos if API fails
        const fallbackOther = [
          { id: '5Q7bUdj5RBk', title: 'Spacious 4.5 BHK Residences', thumbnail: 'https://img.youtube.com/vi/5Q7bUdj5RBk/mqdefault.jpg' },
          { id: 'ePhypZbTu-8', title: 'Work Progress | April 2026', thumbnail: 'https://img.youtube.com/vi/ePhypZbTu-8/mqdefault.jpg' },
          { id: 'kGENK2zARWs', title: 'Work Progress | March 2026', thumbnail: 'https://img.youtube.com/vi/kGENK2zARWs/mqdefault.jpg' },
        ];
        
        const fallbackLatest = [fallbackOther[0]];
        const fallbackRemaining = fallbackOther.slice(1);
        
        const fallbackInterleaved: Video[] = [];
        const fallbackMax = Math.max(manualTestimonials.length, fallbackRemaining.length);
        for (let i = 0; i < fallbackMax; i++) {
          if (i < manualTestimonials.length) fallbackInterleaved.push(manualTestimonials[i]);
          if (i < fallbackRemaining.length) fallbackInterleaved.push(fallbackRemaining[i]);
        }
        
        setVideos([...fallbackLatest, ...fallbackInterleaved]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchVideos();
  }, []);

  const nextVideo = () => {
    if (videos.length > 0) {
      setCurrentIndex((prev) => (prev + 1) % videos.length);
    }
  };

  const prevVideo = () => {
    if (videos.length > 0) {
      setCurrentIndex((prev) => (prev - 1 + videos.length) % videos.length);
    }
  };

  return (
    <section id="videos" className="py-24 bg-gray-50">
      <div className="container mx-auto px-4">
        <div className="text-center max-w-3xl mx-auto mb-16">
          <h4 className="text-primary font-medium tracking-widest uppercase mb-2">Video Gallery</h4>
          <h2 className="text-4xl md:text-5xl font-serif mb-6 text-gray-900">Latest Updates</h2>
          <p className="text-gray-600 text-lg">
            Stay up to date with the latest progress and walkthroughs of <a href="https://www.legacylifespaces.com" target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">Legacy</a> Kairos.
          </p>
        </div>

        <div className="max-w-5xl mx-auto relative">
          {isLoading ? (
            <div className="w-full aspect-video rounded-3xl bg-gray-200 flex items-center justify-center mb-6">
              <Loader2 className="w-12 h-12 text-primary animate-spin" />
            </div>
          ) : videos.length > 0 ? (
            <>
              {/* Main Video Player */}
              <div className="relative w-full aspect-video rounded-3xl overflow-hidden shadow-2xl border-4 border-white bg-black mb-6">
                <AnimatePresence mode="wait">
                  <motion.iframe
                    key={currentIndex}
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0, scale: 1.05 }}
                    transition={{ duration: 0.4 }}
                    className="absolute top-0 left-0 w-full h-full"
                    src={`https://www.youtube.com/embed/${videos[currentIndex].id}?autoplay=0&rel=0`}
                    title={videos[currentIndex].title}
                    frameBorder="0"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowFullScreen
                  />
                </AnimatePresence>
              </div>

              {/* Navigation Arrows */}
              <button 
                onClick={prevVideo}
                className="absolute top-[40%] -left-4 md:-left-12 -translate-y-1/2 bg-white text-primary p-3 rounded-full shadow-xl hover:bg-primary hover:text-white transition-colors z-10"
              >
                <ChevronLeft size={28} />
              </button>
              <button 
                onClick={nextVideo}
                className="absolute top-[40%] -right-4 md:-right-12 -translate-y-1/2 bg-white text-primary p-3 rounded-full shadow-xl hover:bg-primary hover:text-white transition-colors z-10"
              >
                <ChevronRight size={28} />
              </button>

              {/* Thumbnails */}
              <div className="flex gap-4 overflow-x-auto pb-4 snap-x hide-scrollbar">
                {videos.map((video, idx) => (
                  <button
                    key={video.id + idx}
                    onClick={() => setCurrentIndex(idx)}
                    className={`relative shrink-0 w-40 aspect-video rounded-xl overflow-hidden snap-center transition-all duration-300 ${
                      currentIndex === idx ? 'ring-4 ring-primary scale-105' : 'opacity-60 hover:opacity-100'
                    }`}
                  >
                    <img 
                      src={video.thumbnail} 
                      alt={video.title}
                      className="w-full h-full object-cover"
                    />
                    <div className="absolute inset-0 bg-black/30 flex items-center justify-center">
                      <PlayCircle className="text-white opacity-80" size={24} />
                    </div>
                  </button>
                ))}
              </div>
            </>
          ) : (
            <div className="text-center py-12 text-gray-500">No videos found.</div>
          )}
        </div>
      </div>
    </section>
  );
}
