"use client"

import { videos as staticVideos } from "@/data";
import { Button } from "@/components/ui/button";
import { Play, X } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { SectionHeader } from "@/components/ui/SectionHeader";
import { useState, useEffect } from "react";
import { fetchYouTubeVideos } from "@/lib/youtube";

const CHANNEL_ID = "UCTFWJlwD2XdToYDwk6XulEA";

export function Videos() {
  const [selectedVideo, setSelectedVideo] = useState(null);
  const [embedError, setEmbedError] = useState(false);
  const [videos, setVideos] = useState(staticVideos);
  const [loading, setLoading] = useState(true);

  // Fetch videos from YouTube RSS feed on component mount
  useEffect(() => {
    const loadVideos = async () => {
      try {
        const fetchedVideos = await fetchYouTubeVideos(CHANNEL_ID, 10);
        if (fetchedVideos.length > 0) {
          setVideos(fetchedVideos);
        }
      } catch (error) {
        console.error('Failed to load YouTube videos:', error);
        // Keep static videos as fallback
      } finally {
        setLoading(false);
      }
    };

    loadVideos();
  }, []);

  const handleVideoClick = (video) => {
    setSelectedVideo(video);
    setEmbedError(false);
  };

  const handleCloseModal = () => {
    setSelectedVideo(null);
    setEmbedError(false);
  };

  const handleEmbedError = () => {
    setEmbedError(true);
    // Redirect to YouTube after a short delay
    setTimeout(() => {
      window.open(`https://www.youtube.com/watch?v=${selectedVideo.videoId}`, '_blank');
      handleCloseModal();
    }, 1500);
  };

  return (
    <section id="videos" className="py-20 bg-primary/20">
      <div className="container px-4">
        <SectionHeader 
          title="Recent Videos" 
          subtitle="Watch the latest from our YouTube channel."
        />

        {loading ? (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-w-4xl mx-auto">
            {[1, 2, 3, 4].map((i) => (
              <div key={i} className="animate-pulse">
                <div className="relative aspect-video rounded-lg bg-muted mb-4" />
                <div className="h-6 bg-muted rounded w-3/4" />
              </div>
            ))}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-w-4xl mx-auto">
            {videos.map((video, index) => (
              <motion.div
                key={video.id}
                onClick={() => handleVideoClick(video)}
                initial={{ opacity: 0, y: 20 }}
                whileInView={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.1 }}
                viewport={{ once: true }}
                className="group cursor-pointer"
              >
                <div className="relative aspect-video rounded-lg bg-black overflow-hidden mb-4 shadow-lg">
                  <img 
                    src={video.thumbnail} 
                    alt={video.title}
                    className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                  />
                  <div className="absolute inset-0 bg-black/20 group-hover:bg-black/30 transition-colors" />
                  <div className="absolute inset-0 flex items-center justify-center">
                     <div className="h-16 w-16 rounded-full bg-red-600/90 backdrop-blur-sm flex items-center justify-center group-hover:bg-red-600 group-hover:scale-110 transition-all">
                        <Play className="fill-white text-white ml-1 h-8 w-8" />
                     </div>
                  </div>
                </div>
                <h3 className="text-lg font-semibold group-hover:text-primary transition-colors">{video.title}</h3>
              </motion.div>
            ))}
          </div>
        )}

        <div className="text-center mt-12">
          <Button variant="secondary" size="lg" asChild>
            <a href="https://www.youtube.com/@TrainSOfRajbari" target="_blank" rel="noopener noreferrer" className="text-lg">
              Visit Channel
            </a>
          </Button>
        </div>
      </div>

      {/* Video Modal */}
      <AnimatePresence>
        {selectedVideo && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={handleCloseModal}
            className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4"
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              onClick={(e) => e.stopPropagation()}
              className="relative w-full max-w-4xl bg-background rounded-lg overflow-hidden shadow-2xl"
            >
              {/* Close Button */}
              <button
                onClick={handleCloseModal}
                className="absolute top-4 right-4 z-10 h-10 w-10 rounded-full bg-black/50 hover:bg-black/70 flex items-center justify-center transition-colors"
              >
                <X className="h-6 w-6 text-white" />
              </button>

              {/* Video Player */}
              <div className="relative aspect-video bg-black">
                {embedError ? (
                  <div className="absolute inset-0 flex items-center justify-center text-white">
                    <div className="text-center">
                      <p className="text-lg mb-2">Embedding disabled for this video</p>
                      <p className="text-sm text-gray-400">Redirecting to YouTube...</p>
                    </div>
                  </div>
                ) : (
                  <iframe
                    src={`https://www.youtube.com/embed/${selectedVideo.videoId}?autoplay=1`}
                    title={selectedVideo.title}
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowFullScreen
                    onError={handleEmbedError}
                    className="w-full h-full"
                  />
                )}
              </div>

              {/* Video Title */}
              <div className="p-4 bg-background">
                <h3 className="text-lg font-semibold">{selectedVideo.title}</h3>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </section>
  );
}
