import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useInView } from 'react-intersection-observer';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation, Pagination } from 'swiper/modules';
import { ChevronLeft, ChevronRight, Image as ImageIcon, Filter, Search, X } from 'lucide-react';
import { Link } from 'react-router-dom';
import { supabase } from '../lib/supabase';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import PageVisibilityWrapper from '../components/PageVisibilityWrapper';
import { Helmet } from "react-helmet";

type PortfolioAlbumWithCover = {
  id: string;
  title: string;
  description: string | null;
  category: string | null;
  cover_image: string | null;
  display_order: number;
  is_featured: boolean;
  image_count: number;
  created_at: string;
  updated_at: string;
};

type PortfolioImage = {
  id: string;
  image_url: string;
  caption: string | null;
  // Add other fields if needed based on your 'portfolio_images' table
};

// Category filters
const CATEGORIES = ['All', 'Wedding', 'Corporate', 'Anniversary', 'Festival', 'Cultural', 'Social'];

// Loading progress animation styles
const loadingProgressVariants = {
  initial: { width: "0%" },
  loading: { 
    width: "90%", 
    transition: { 
      duration: 1.5, 
      ease: "easeInOut" 
    } 
  },
  complete: { 
    width: "100%", 
    transition: { 
      duration: 0.3, 
      ease: "easeOut" 
    } 
  }
};

const Gallery = () => {
  const [albums, setAlbums] = useState<PortfolioAlbumWithCover[]>([]);
  const [filteredAlbums, setFilteredAlbums] = useState<PortfolioAlbumWithCover[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeCategory, setActiveCategory] = useState('All');
  const [activeSliderIndex, setActiveSliderIndex] = useState<number | null>(null);
  const [albumImages, setAlbumImages] = useState<PortfolioImage[]>([]);
  const [isModalLoading, setIsModalLoading] = useState(false);
  const [modalError, setModalError] = useState<string | null>(null);
  
  const [ref, inView] = useInView({
    triggerOnce: true,
    threshold: 0.1,
  });

  // Fetch initial albums
  useEffect(() => {
    const fetchAlbums = async () => {
      try {
        setLoading(true);
        setError(null);
        const { data, error } = await supabase.rpc('get_portfolio_albums_with_cover');
        if (error) throw error;
        const albumsData = data as PortfolioAlbumWithCover[];
        setAlbums(albumsData);
        setFilteredAlbums(albumsData);
      } catch (err) {
        console.error('Error fetching portfolio albums:', err);
        setError('Failed to load portfolio albums');
      } finally {
        setLoading(false);
      }
    };
    fetchAlbums();
  }, []);

  // Filter albums when category changes
  useEffect(() => {
    if (activeCategory === 'All') {
      setFilteredAlbums(albums);
    } else {
      setFilteredAlbums(albums.filter(album => album.category === activeCategory));
    }
  }, [activeCategory, albums]);

  // Function to fetch images for a specific album
  const fetchAlbumImages = async (albumId: string) => {
    if (!albumId) {
      setModalError("Invalid album ID");
      return;
    }
    
    console.log('[Gallery Modal] Fetching images for album ID:', albumId);
    setIsModalLoading(true);
    setModalError(null);
    setAlbumImages([]); // Clear previous images
    
    try {
      // Simplified query that avoids reliance on specific columns
      const { data, error } = await supabase
        .from('portfolio_images')
        .select('id, image_url, album_id')
        .eq('album_id', albumId);
        
      console.log('[Gallery Modal] Supabase response:', { 
        data: data?.length || 0, 
        error: error?.message || 'none',
        albumId 
      });

      if (error) {
        throw new Error(`Database error: ${error.message}`);
      }

      if (!data || data.length === 0) {
        console.log('[Gallery Modal] No images found for album ID:', albumId);
        setModalError(`No images found for this album. Please add some images or try another album.`);
        return;
      }
      
      // Validate image data before setting state
      const validImages = data.filter(img => img.image_url && img.id);
      
      if (validImages.length === 0) {
        setModalError('The images in this album don\'t have proper URLs');
        return;
      }
      
      setAlbumImages(validImages as PortfolioImage[]);
      console.log('[Gallery Modal] Successfully loaded', validImages.length, 'images');

    } catch (err) {
      console.error('[Gallery Modal] Error fetching album images:', err);
      const message = err instanceof Error ? err.message : 'An unknown error occurred';
      setModalError(`Failed to load album images. ${message}`);
    } finally {
      setIsModalLoading(false);
    }
  };

  // Handle opening the modal
  const handleOpenModal = (index: number) => {
    console.log('[Gallery] Opening modal for album index:', index);
    const album = filteredAlbums[index];
    console.log('[Gallery] Album details:', album);
    
    setActiveSliderIndex(index);
    if (album?.id) {
      fetchAlbumImages(album.id);
    } else {
      console.error('[Gallery] No album ID found for index:', index);
      setModalError('Could not find album ID to fetch images');
    }
  };
  
  // Handle closing the modal
  const handleCloseModal = () => {
    console.log('[Gallery] Closing modal');
    setActiveSliderIndex(null);
    setAlbumImages([]); // Clear images when closing
    setModalError(null); 
  };

  // Add debug log for rendered state
  useEffect(() => {
    console.log('[Gallery] Current state:', { 
      albumCount: filteredAlbums.length,
      activeSliderIndex,
      albumImagesCount: albumImages.length,
      modalError,
      isModalLoading
    });
  }, [filteredAlbums.length, activeSliderIndex, albumImages.length, modalError, isModalLoading]);

  return (
    <div>
      <Helmet>
        <title>Gallery | Amoeba Productions - Event Photos & Highlights Patna</title>
        <meta name="description" content="View the gallery of Amoeba Productions. Explore event photos, highlights, and memories from weddings, corporate events, and celebrations in Patna, Bihar, and beyond." />
        <meta name="keywords" content="Event Gallery Patna, Event Photos, Amoeba Productions Gallery, Wedding Photos, Corporate Event Photos, Event Highlights, Patna, Bihar, Delhi, Ranchi" />
        <link rel="canonical" href="https://www.amoebaproductions.com/gallery" />
        <meta property="og:title" content="Gallery | Amoeba Productions - Event Photos & Highlights Patna" />
        <meta property="og:description" content="Explore the gallery of Amoeba Productions. See highlights from our best events in Patna and across Bihar." />
        <meta property="og:image" content="https://www.amoebaproductions.com/images/logo.png" />
        <meta property="og:url" content="https://www.amoebaproductions.com/gallery" />
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:title" content="Gallery | Amoeba Productions - Event Photos & Highlights Patna" />
        <meta name="twitter:description" content="View event photos and highlights from Amoeba Productions in Patna, Bihar, and beyond." />
        <meta name="twitter:image" content="https://www.amoebaproductions.com/images/logo.png" />
      </Helmet>
      {/* Structured Data for Gallery Albums */}
      <script type="application/ld+json">
        {JSON.stringify({
          '@context': 'https://schema.org',
          '@type': 'ImageGallery',
          'name': 'Amoeba Productions Event Gallery',
          'description': 'Event photos, highlights, and memories from Amoeba Productions.',
          'url': 'https://www.amoebaproductions.com/gallery',
          'image': filteredAlbums.map(album => album.cover_image).filter(Boolean),
          'hasPart': filteredAlbums.map(album => ({
            '@type': 'ImageGallery',
            'name': album.title,
            'description': album.description,
            'image': album.cover_image,
            'url': `https://www.amoebaproductions.com/gallery#${album.id}`
          }))
        })}
      </script>
      {/* Hero section */}
      <section className="relative py-20 bg-gray-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            className="text-center mb-12"
          >
            <h1 className="text-4xl md:text-5xl font-playfair font-bold mb-4">
              Event Portfolio
            </h1>
            <p className="text-lg text-gray-600 max-w-3xl mx-auto">
              Explore our collection of successful events and celebrations
            </p>
          </motion.div>
        </div>
      </section>

      {/* Gallery section */}
      <section className="py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Category Filters */}
          <div className="flex flex-wrap justify-center gap-2 mb-10">
            {CATEGORIES.map((category) => (
              <button
                key={category}
                onClick={() => setActiveCategory(category)}
                className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                  activeCategory === category
                    ? 'bg-primary text-white'
                    : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                }`}
              >
                {category}
              </button>
            ))}
          </div>

          {loading ? (
            <div className="py-12 flex justify-center items-center">
              <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
            </div>
          ) : error ? (
            <div className="py-12 text-center">
              <p className="text-red-500">{error}</p>
            </div>
          ) : filteredAlbums.length === 0 ? (
            <div className="py-12 text-center">
              <p className="text-gray-500">No albums found in this category</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8" ref={ref}>
              {filteredAlbums.map((album, idx) => (
                <motion.div
                  key={album.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={inView ? { opacity: 1, y: 0 } : {}}
                  transition={{ duration: 0.5, delay: idx * 0.1 }}
                  className="bg-white rounded-xl shadow-lg overflow-hidden cursor-pointer group"
                  onClick={() => handleOpenModal(idx)} 
                >
                    <div className="relative aspect-w-16 aspect-h-9">
                      {album.cover_image ? (
                        <img
                          src={album.cover_image}
                          alt={album.title}
                        className="w-full h-64 object-cover group-hover:scale-105 transition-transform duration-300"
                          onError={(e) => {
                            (e.target as HTMLImageElement).src = 'https://via.placeholder.com/400x250?text=Image+Not+Found';
                          }}
                        />
                      ) : (
                        <div className="w-full h-64 bg-gray-200 flex items-center justify-center">
                          <ImageIcon className="w-12 h-12 text-gray-400" />
                        </div>
                      )}
                    <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-40 transition-opacity duration-300 flex items-center justify-center">
                      <span className="text-white text-lg font-semibold opacity-0 group-hover:opacity-100 transition-opacity duration-300">View Preview</span>
                      </div>
                      {album.is_featured && (
                      <div className="absolute top-4 right-4 bg-primary text-white px-3 py-1 rounded-full text-xs font-semibold">Featured</div>
                      )}
                      <div className="absolute bottom-4 right-4 bg-black bg-opacity-60 text-white px-3 py-1 rounded-full text-xs">
                        {album.image_count} photos
                      </div>
                    </div>
                    <div className="p-6">
                    <h3 className="text-xl font-bold mb-2 group-hover:text-primary transition-colors bg-clip-text text-transparent bg-gradient-to-r from-orange-500 to-blue-600">{album.title}</h3>
                    <p className="text-gray-800 text-sm mb-3 line-clamp-2">{album.description}</p>
                      {album.category && (
                        <div className="mt-4">
                        <span className="inline-block bg-gradient-to-r from-orange-500/20 to-blue-600/20 text-gray-900 px-3 py-1 rounded-full text-xs">
                            {album.category}
                          </span>
                        </div>
                      )}
                    <Link 
                       to={`/portfolio/${album.id}`}
                       className="text-sm text-primary hover:underline mt-2 inline-block"
                       onClick={(e) => e.stopPropagation()} // Prevent modal open when clicking link
                     >
                       View Full Album
                     </Link>
                    </div>
                </motion.div>
              ))}
            </div>
          )}

          {/* Image Slider Modal */}
          {activeSliderIndex !== null && (
            <div 
               className="fixed inset-0 z-[100] bg-black/90 flex items-center justify-center p-4 animate-fade-in"
               onClick={handleCloseModal} // Close on backdrop click
            >
              <div 
                 className="bg-white rounded-lg shadow-xl max-w-4xl w-full h-[80vh] relative flex flex-col"
                 onClick={(e) => e.stopPropagation()} // Prevent close when clicking inside modal
              >
                {/* Close Button */}
                <button
                  onClick={handleCloseModal}
                  className="absolute -top-4 -right-4 z-50 text-white bg-gray-800 rounded-full p-1 hover:bg-gray-600 transition-colors"
                  aria-label="Close modal"
                >
                  <X className="w-5 h-5" />
                </button>
                
                {/* Modal Header */}
                <div className="p-4 border-b border-gray-200">
                   <h2 className="text-xl font-bold text-gray-800">
                     {filteredAlbums[activeSliderIndex]?.title || 'Album Preview'}
                   </h2>
                </div>
                
                {/* Modal Body with Slider */}
                <div className="flex-grow overflow-hidden p-4 relative">
                   {isModalLoading ? (
                     <div className="absolute inset-0 flex justify-center items-center flex-col">
                       <div className="w-64 h-2 bg-gray-200 rounded-full overflow-hidden mb-4">
                         <motion.div
                           className="h-full bg-gradient-to-r from-orange-500 via-blue-500 to-blue-600 rounded-full relative shimmer-animation"
                           variants={loadingProgressVariants}
                           initial="initial"
                           animate="loading"
                         />
                       </div>
                       <p className="text-gray-500 text-sm">Loading album images...</p>
                     </div>
                   ) : modalError ? (
                     <div className="absolute inset-0 flex justify-center items-center flex-col">
                       <p className="text-red-500 mb-2">{modalError}</p>
                       <p className="text-gray-500 text-sm">Try refreshing the page or contact support if the issue persists.</p>
                     </div>
                   ) : albumImages.length === 0 ? (
                      <div className="absolute inset-0 flex justify-center items-center">
                         <p className="text-gray-500">No images found for this album.</p>
                      </div>
                   ) : (
                     <Swiper
                       modules={[Navigation, Pagination]}
                       spaceBetween={10}
                       slidesPerView={1}
                       navigation={{
                           prevEl: '.album-prev',
                           nextEl: '.album-next',
                       }}
                       pagination={{ clickable: true, dynamicBullets: true }}
                       loop={albumImages.length > 1}
                       className="w-full h-full"
                     >
                       {albumImages.map((image) => (
                         <SwiperSlide key={image.id} className="flex items-center justify-center">
                           <img
                             src={image.image_url}
                             alt={`Album image ${image.id}`}
                             className="max-w-full max-h-full object-contain rounded"
                             onError={(e) => {
                               (e.target as HTMLImageElement).src = 'https://via.placeholder.com/400x300?text=Image+Loading+Error';
                             }}
                           />
                         </SwiperSlide>
                       ))}
                       {/* Custom Navigation Buttons */}
                       {albumImages.length > 1 && (
                         <>
                           <button className="album-prev absolute left-2 top-1/2 -translate-y-1/2 z-10 p-2 bg-black/40 hover:bg-black/60 rounded-full text-white transition-colors">
                             <ChevronLeft className="w-6 h-6" />
                           </button>
                           <button className="album-next absolute right-2 top-1/2 -translate-y-1/2 z-10 p-2 bg-black/40 hover:bg-black/60 rounded-full text-white transition-colors">
                             <ChevronRight className="w-6 h-6" />
                           </button>
                         </>
                       )}
                     </Swiper>
                   )}
                </div>
              </div>
            </div>
          )}
        </div>
      </section>
    </div>
  );
};

export default Gallery;