import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';

const MOCK_GALLERY = [
  {
    _id: 'g1',
    title: 'Young Scientists',
    category: 'Classrooms',
    imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBx2Nb9_5Fn1ZqobpBG1OandJaYuMKScJA-tGpFyZ_QbiQXCragyAsZUUgmf7eBqI0728vheS_J3gfJFLe2vOfyJ-TXtnuT_gR-w1SAqiQ-fhqEbPid8FNkwX2brkBm4TrqBETGbX2nEsNhykJoaC2T5iH9YTuT8bRtqa9ZrGaUko1Q2j_hOocYQcZ7t1iPZF-6FNZIFurvvP4WFO75FEFddpNr3j-Cvb_u1oDUMx1KE3e85yTFROOF_w'
  },
  {
    _id: 'g2',
    title: 'Our Campus Turrets',
    category: 'Campus',
    imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuCmBjZMTW-YrzdgkScySRMdUh-iQRBtwVeIYcfOJqFfm7exbY6SeY2k7HxqQu4q3zfXT5yJlAYu0iGZsQHj8yFMAAN1l2bEXoAwnMaktUtIeH6QfvMQKQhF8MUAbmfDJw8vHQc8tvDIN-OagXSDDAAj4JEig76DYE7zH1NuAO_p13qGaRIiQjZ7ihhYNeDYmlSK8jWnBAAwVjoLdnPJ9Du9mrgs0GvjOKPWk-Rn3rR9jq4MMivp0lnapQ'
  },
  {
    _id: 'g3',
    title: 'Soccer Tournament',
    category: 'Sports',
    imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuEn97qqps3C6hCtAC6vYmwAo8pUikr_n_zw4uvgELmmRHzAJEMFPMIh60V3MrR9gEmAbJ4PGy3oe5NhcN6AfMy7-OpM_IzVKKiyfUgAKMt_OmV_DgJmASJM2yzjqhW0uPzl_SrfjJBGRZxdnBDEY6Dr6xUxeka-aLx04XDW19KVVxxXBsUvO79Rva2tQvYmwZo2-E9ghOTSxyIuUONS2MPTVd8uVEUO8L1n26sULs1rPrjZJWhiUk0_Q'
  },
  {
    _id: 'g4',
    title: 'Annual Play 2023',
    category: 'Events',
    imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuDdyrz2H6Z0SFTMlao-n-yC6dw0HY_IEwKVyPs-tNABx1VeYeKK2IQidH41johdDDQMElrkVzIn2QpqBPxTAzxLJvthL9Plm5SskchqUDK4PkVartI-tf2vxiYsl0hNLMzfkzxWgqG17zlTj-8znX4zHnVeE4MFsJhLZZJqlE0mP25kZ3Nxo440pDEPH7XNvrm5T7BnZxgajO6RtpZWGu4qxH_s1hwa7DMMXupT6SaSNLWnRF2gNdzlPA'
  },
  {
    _id: 'g5',
    title: 'Creative Art Studio',
    category: 'Classrooms',
    imageUrl: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBdhX8ep92Kl35WRm3YZH5kF1xNviFtWuD27PyFsUPnDPz_XTCPZHmks8i6-FjjSzPtz_m47TivgoQklmk_uK-u9NsKMlR_sEbk3j3gQMo-feygDATtrYpxwUogvPaBYKC553qdF0ZYrOtGhmsmAInKfcWfv_w9vT4f1gqjnF1UXWC9pndqCABxmvxTRJl7NqGSu-yzR7uiwlBNS32ufZPeJBkdOY95hiiFyx3e7c-rOBGy5FYO4AeVvw'
  }
];

export default function Gallery() {
  const [gallery, setGallery] = useState([]);
  const [categoryFilter, setCategoryFilter] = useState('All');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchGallery();
  }, []);

  const fetchGallery = async () => {
    try {
      setLoading(true);
      const res = await axios.get('http://localhost:5000/api/gallery');
      if (res.data && res.data.length > 0) {
        setGallery(res.data);
      } else {
        setGallery(MOCK_GALLERY);
      }
    } catch (err) {
      console.error("Failed to fetch gallery:", err);
      setGallery(MOCK_GALLERY);
    } finally {
      setLoading(false);
    }
  };

  const categories = ['All', 'Campus', 'Classrooms', 'Events', 'Sports'];

  const filteredGallery = gallery.filter(item => {
    return categoryFilter === 'All' || item.category === categoryFilter;
  });

  return (
    <div className="min-h-screen pt-16">
      <Navbar />
      <main>
        
        <section className="relative min-h-[50vh] flex flex-col items-center justify-center text-center px-4 md:px-8 overflow-hidden pt-0 bg-gradient-to-br from-primary-container/10 via-surface to-secondary-container/5">
          <div className="absolute inset-0 z-0">
            <div className="absolute top-10 left-10 animate-float">
              <span className="material-symbols-outlined text-primary-container text-7xl opacity-40">cloud</span>
            </div>
            <div className="absolute top-40 right-20 animate-float-delayed">
              <span className="material-symbols-outlined text-secondary-container text-9xl opacity-30">auto_awesome</span>
            </div>
            <div className="absolute bottom-20 left-1/4 animate-float">
              <span className="material-symbols-outlined text-tertiary-container text-6xl opacity-30">rocket_launch</span>
            </div>
          </div>
          <div className="relative z-10 max-w-4xl">
            <h1 className="font-headline font-bold text-4xl md:text-5xl text-primary mb-6 drop-shadow-sm">School Gallery</h1>
            <p className="font-body-lg text-body-lg text-on-surface-variant max-w-2xl mx-auto mb-10 leading-relaxed">
              Every Picture Tells a Story of Learning, Friendship, and Success. Wander through our captured memories of magical moments and academic milestones.
            </p>

            <div className="flex flex-wrap justify-center gap-3 mb-12">
              {categories.map(cat => (
                <button 
                  key={cat}
                  onClick={() => setCategoryFilter(cat)}
                  className={`px-6 py-2 rounded-full font-semibold transition-all ${
                    categoryFilter === cat 
                      ? 'bg-primary text-on-primary shadow-lg scale-105' 
                      : 'bg-surface border border-outline-variant/30 text-on-surface-variant hover:bg-primary-container/20'
                  }`}
                >
                  {cat}
                </button>
              ))}
            </div>
          </div>
        </section>

        {/* Gallery Grid */}
        <section className="bg-surface py-16 px-4 md:px-8">
          <div className="max-w-7xl mx-auto">
            {loading ? (
              <div className="text-center py-20 text-on-surface-variant">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
                <p>Loading gallery items...</p>
              </div>
            ) : filteredGallery.length === 0 ? (
              <div className="text-center py-20 text-on-surface-variant">
                <span className="material-symbols-outlined text-6xl mb-4">image_not_supported</span>
                <p className="text-lg">No photos found in this category.</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-8">
                {filteredGallery.map((item) => (
                  <div key={item._id} className="group relative overflow-hidden rounded-xl bg-white shadow-md border border-surface-variant/50 transition-all duration-300 hover:-translate-y-2 hover:shadow-xl aspect-[4/3]">
                    <img 
                      className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" 
                      src={item.imageUrl} 
                      alt={item.title || "Gallery Item"} 
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-primary/80 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-end p-6">
                      <div className="text-on-primary">
                        <p className="font-headline font-semibold text-lg leading-tight mb-1">{item.title || 'Campus Moment'}</p>
                        <p className="text-xs opacity-90">{item.category}</p>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </section>

        {/* Albums Spotlight */}
        <section className="py-16 px-4 md:px-8 bg-white border-t border-outline-variant/20">
          <div className="max-w-7xl mx-auto">
            <div className="flex justify-between items-end mb-12">
              <div>
                <h2 className="font-headline font-bold text-2xl text-primary mb-2">Photo Albums</h2>
                <p className="text-on-surface-variant">Collections from our most cherished events.</p>
              </div>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
              <div className="group cursor-pointer">
                <div className="relative aspect-video rounded-lg overflow-hidden shadow-md mb-4 border-4 border-white">
                  <img className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" src="https://lh3.googleusercontent.com/aida-public/AB6AXuViq3Geo3M9flkb1kgtlpTCvUbacrtSNmcxakF8iqqXjA52l21TRzUDPTyt4qn7GV6Nzt-hVoGjPDny7C72law9Dmgv3F5XxuFTExTYsDAfCW-j8mNEGgzfWxzuGdDDDIbwgmKw40ck61p1SVG_hOT1PyU0h4EMv94qSClwPsmKilOGrrxjC-2Pfg1LGvXJv1AsdbgV8I2aUmwZtMPzHMuYTnrnrwHnCH7pTSyB3jcFgNh5On4R_UMXg" alt="Annual Day" />
                  <div className="absolute top-4 right-4 bg-surface/90 backdrop-blur px-3 py-1 rounded-full text-xs text-primary font-bold shadow-sm">
                    48 Photos
                  </div>
                </div>
                <h3 className="font-headline font-semibold text-lg group-hover:text-primary transition-colors">Annual Day 2024</h3>
                <p className="text-sm text-on-surface-variant">A celebration of talent and dreams.</p>
              </div>

              <div className="group cursor-pointer">
                <div className="relative aspect-video rounded-lg overflow-hidden shadow-md mb-4 border-4 border-white">
                  <img className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" src="https://lh3.googleusercontent.com/aida-public/AB6AXuCvrA-roV-XHHxDKa1yFwzMrUdQ3b8KCXIJrvm8CNcW3V7V-Z6tSOEDP4JEFp8ahGWH4mOGuJjY-NUswcPbefXnJaGb1wmY5pmbDAeUq0djIqSBmMHp-8IFFw37QJy878jjjWRcoHBo_dQljxr7yrvbMFZTQ29MvOT7FkxCEd0i0InXBG2QSHfxmTWLKgZRklZXrhrX00xTE1Cp_2Sb7AKCwkGStrrq8FYFmSmctb-kEk84qp_2Ynw6xQ" alt="Sports Meet" />
                  <div className="absolute top-4 right-4 bg-surface/90 backdrop-blur px-3 py-1 rounded-full text-xs text-primary font-bold shadow-sm">
                    125 Photos
                  </div>
                </div>
                <h3 className="font-headline font-semibold text-lg group-hover:text-primary transition-colors">Sports Meet</h3>
                <p className="text-sm text-on-surface-variant">Unity, strength, and athletic excellence.</p>
              </div>

              <div className="group cursor-pointer">
                <div className="relative aspect-video rounded-lg overflow-hidden shadow-md mb-4 border-4 border-white">
                  <img className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" src="https://lh3.googleusercontent.com/aida-public/AB6AXuCM380_6uXHD7p7KEoX4DeivcUJqqeICxtItrCiW79V2f7EQaKR-v4Pp-z5v-Vo9NC-PLlKKmcyNWtJ6CRQO-gSIsbW04JIlnUmmQiLIelPwq7vKyD_O3tMpizruWR7Q1fRpBOqyudZ8_FC7I8xdV-niV4fhwcYLK6uXiry7s6H_Pm6FozMRzX0ai07o2RL2QmB1_jA-sV0yyrd5vMWFUDcDzl55hx3KiiKxmS03JLTWqX9HA0jh6Fkiw" alt="Science Exhibition" />
                  <div className="absolute top-4 right-4 bg-surface/90 backdrop-blur px-3 py-1 rounded-full text-xs text-primary font-bold shadow-sm">
                    32 Photos
                  </div>
                </div>
                <h3 className="font-headline font-semibold text-lg group-hover:text-primary transition-colors">Science Exhibition</h3>
                <p className="text-sm text-on-surface-variant">Inquisitive minds exploring the future.</p>
              </div>
            </div>
          </div>
        </section>
      </main>
      <Footer />
    </div>
  );
}
