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

const YOUTUBE_API_KEY = YOUTUBE_CONFIG.API_KEY;
const CHANNEL_ID = YOUTUBE_CONFIG.CHANNEL_ID; // Legacy Lifespaces

interface ShortVideo {
  id: string;
  title: string;
}

export default function ShortsGallery() {
  const [shorts, setShorts] = useState<ShortVideo[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchShorts = async () => {
      try {
        // Search for "Testimonial" videos on the channel
        const response = await fetch(
          `https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=${CHANNEL_ID}&q=Testimonial&maxResults=4&type=video&key=${YOUTUBE_API_KEY}`
        );
        const data = await response.json();
        
        if (data.items && data.items.length > 0) {
          const fetchedShorts = data.items.map((item: any) => ({
            id: item.id.videoId,
            title: item.snippet.title,
          }));
          setShorts(fetchedShorts);
        } else {
          throw new Error("No testimonials found");
        }
      } catch (error) {
        console.error('Error fetching YouTube shorts:', error);
        // Fallback shorts if API fails
        setShorts([
          { id: 'TvDTbaB-9JY', title: 'Testimonial - Mr. Sagar & Mrs. Bharti' },
          { id: 'wGIhuKVfnm8', title: 'Testimonial - Mr. Ram & Mrs. Mamta' },
          { id: 'AHGReBLy1PQ', title: 'Testimonial - Mr. Harshad & Mrs. Trupti' },
          { id: 'RKF6dERiAd4', title: 'Testimonial - Mr. Mitesh Sharma' },
        ]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchShorts();
  }, []);

  return (
    <section id="shorts" className="py-24 bg-gray-900 text-white">
      <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">Shorts</h4>
          <h2 className="text-4xl md:text-5xl font-serif mb-6">Quick Snippets</h2>
          <p className="text-gray-400 text-lg">
            Hear directly from our happy residents and take a quick look at <a href="https://www.legacylifespaces.com" target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">Legacy</a> Kairos.
          </p>
        </div>

        {isLoading ? (
          <div className="flex justify-center py-12">
            <Loader2 className="w-12 h-12 text-primary animate-spin" />
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto">
            {shorts.map((short, idx) => (
              <motion.div
                key={short.id + idx}
                initial={{ opacity: 0, y: 20 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                transition={{ delay: idx * 0.1 }}
                className="relative w-full aspect-[9/16] rounded-2xl overflow-hidden shadow-2xl border border-gray-800 bg-black group"
              >
                <iframe
                  className="absolute top-0 left-0 w-full h-full"
                  src={`https://www.youtube.com/embed/${short.id}?autoplay=0&rel=0&modestbranding=1`}
                  title={short.title}
                  frameBorder="0"
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                  allowFullScreen
                />
              </motion.div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}
