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_EVENTS = [
  {
    _id: 'event1',
    title: 'Annual Science Fair 2024: A Galaxy of Innovations',
    description: 'This year\'s science fair witnessed an incredible array of projects ranging from sustainable energy models to neural-link prototypes. Our students showcased not just their technical skills, but their boundless imagination.',
    category: 'Spotlight',
    image: 'https://lh3.googleusercontent.com/aida-public/AB6AXuDPaNrSveAEX6qyaH1dprofTwqha-6IV5IsWajOauyJ-RXj69RuxkaHqqnHV8-B5FJu-F6vjyoidA3rhrplesnvCDWktoS5oAvqi1jWhTUsS256lGRbwe34_dB_ngXV6-5btQZYpv1XRrqjfFq8Yc8GQFku2jpBESfb6iUmqwl7KTgPqxKC5bn80Q7cExKIwgvDMo9LoPG_QDKpvvf-wMgDGw4HuNQVd29w02Qk6iPC6_ZL31_rGo7xLw',
    date: new Date('2024-10-12T00:00:00Z').toISOString()
  },
  {
    _id: 'event2',
    title: 'Robotics Team Wins Silver at Nationals',
    description: 'Our \'Lumina Sparks\' team secured the second position at the prestigious Inter-School Robotics League, demonstrating advanced mechanical build and programming expertise.',
    category: 'Competition',
    image: 'https://lh3.googleusercontent.com/aida-public/AB6AXuCzavXstEIEo__mWPga-XMrOLcf59ZMNB_CPxAfsVdCGDe8AmLqXoiBRBe_-emhvW67vD-ruDCtE5TxBO2snzRC-_iedpmTSTt1_AErr0cVn0Or4uD9gqnoVbiBqgjiRCw3PJIelnQH_Xw2nIbLePzCM8Lov2zAThxzJBIJP1oSp_Dlq5VPOH8-_iujfki20m0Coivr6qsvwPgJ6EHzCUbLJNst2n90H4s-UPl12n6NmZT4H5Gz9hJFYg',
    date: new Date('2024-10-10T00:00:00Z').toISOString()
  },
  {
    _id: 'event3',
    title: 'Inter-School Debate Championship',
    description: 'Mastering the art of persuasion, our senior students triumphed in the regional debate finals last weekend, tackling topics of global governance and environmental ethics.',
    category: 'Academics',
    image: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBTTV3ufxnSsdLiTuGW7L8bEewoRiU_OqvBu-8fQ7-GIfHlc1IfFTOPGizEGri0Rl8HD6OmzQh6ZLZm5Os3U8pZ_oEHssxoP9XijcNrmQTsPIpMIACTUK5zHHeyp_DbYI4uP-Vxiz_BWA2d7Okp_zd7XEJ_dinnEythRdQzqKjdoyhTqi8ESqDYa_02P9PyEUglwPgC11BQXKgWNNkElbV_Ya9Bdpj112LnMa1QHmIa_ewuq2cBROZB-A',
    date: new Date('2024-10-05T00:00:00Z').toISOString()
  },
  {
    _id: 'event4',
    title: 'Green Campus Initiative Phase II',
    description: 'Lumina Academy takes another step towards zero-waste with our new student-led composting facility and vertical organic garden, providing fresh herbs for our cafeteria.',
    category: 'Sustainability',
    image: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBfJGm3VW1bb7etYbPfcDHa5b0IfvhatlMonSig0ZuO2w8UjtDuOOykyRA2yV2rbkv0YYVgUgsSq8TxQGTIeM3GVjgZLND752cKVejjWmc83xvry99PVrdm9vw83lQk-4o57aaMZI21Dt6GrfII_Nid1lIqrwZQO0jcSHu9jUwlrhUypHyB5fnqFMZxB2BXDGZAwl4nX-6EpDOn2MNwz4igMRLkrmkTPxe2Q_zazbKcUIr93zdij3-_2g',
    date: new Date('2024-10-01T00:00:00Z').toISOString()
  },
  {
    _id: 'event5',
    title: 'Annual Sports Day',
    description: 'A day of athletic prowess and team spirit. Join us on the main field for various track and field events, relay races, and the grand drills.',
    category: 'Sports',
    image: '',
    date: new Date('2024-10-25T00:00:00Z').toISOString()
  },
  {
    _id: 'event6',
    title: 'Halloween Storytelling Carnival',
    description: 'Get ready for spooky tales, magical puppet shows, and costume ramp walks at our annual elementary block library festival.',
    category: 'Carnival',
    image: '',
    date: new Date('2024-10-31T00:00:00Z').toISOString()
  }
];

export default function NewsEvents() {
  const [events, setEvents] = useState([]);
  const [loading, setLoading] = useState(true);

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

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

  // Extract spotlight, news list, and timeline events
  const spotlightEvent = events.find(e => e.category === 'Spotlight' || e.image) || events[0];
  const newsList = events.filter(e => e._id !== (spotlightEvent?._id || '') && e.image);
  const timelineEvents = events.filter(e => !e.image || e.category === 'Sports' || e.category === 'Carnival');

  return (
    <div className="min-h-screen pt-16">
      <Navbar />
      <main className="pt-0">
        
        <section className="relative min-h-[50vh] flex items-center overflow-hidden bg-gradient-to-br from-primary-container/20 via-surface to-secondary-container/10 px-4 md:px-8 py-16">
          <div className="absolute inset-0 z-0">
            <img alt="Background Hero" className="w-full h-full object-cover opacity-30 mix-blend-overlay" src="https://lh3.googleusercontent.com/aida/AP1WRLszFuEq5teuoDu0canzgobK3Ch6X_aF72CZKvyTp4Y32IEW_rhOVei6Kpc3Eu7uOgA7JboRsdakOOqFhQTLmfsbwE1oOlbAgtI_iX5rNhfzdNyvKNBrsi_fGiIUoxpa8cezzFg2n7s-k6T9opHGalfNXzcZwP2WZKOSSGiWdZG-qSQaDKs73vz3YBip2sRVVniBJo7v7cCpCNOMMUgdtIxrw8ctmYyNO2G-f3HCL1Cz3Wk3-Ijia5ImX4M"/>
          </div>
          <div className="relative z-10 grid md:grid-cols-2 gap-gutter items-center max-w-7xl mx-auto w-full">
            <div className="space-y-6">
              <span className="inline-block bg-primary text-on-primary px-4 py-1 rounded-full text-label-sm font-label-sm tracking-widest uppercase">What's New</span>
              <h1 className="font-headline font-bold text-[40px] md:text-[56px] leading-tight text-primary">News &amp; Events</h1>
              <p className="font-body-lg text-body-lg text-on-surface-variant max-w-lg">
                Stay Updated with Everything Happening at Our School. From academic milestones to whimsical celebrations, explore the magic of learning at Stellar Academy.
              </p>
              <div className="flex gap-4">
                <a className="bg-primary text-on-primary px-8 py-3 rounded-full font-label-md hover:scale-105 transition-all shadow-lg shadow-primary/25" href="#featured">Explore News</a>
                <a className="border-2 border-primary text-primary px-8 py-3 rounded-full font-label-md hover:bg-primary/5 transition-all" href="#calendar">View Calendar</a>
              </div>
            </div>
            <div className="hidden md:flex justify-center items-center relative">
              <div className="relative w-80 h-80 rounded-full bg-secondary-container/30 floating flex items-center justify-center">
                <span className="material-symbols-outlined text-[120px] text-primary" style={{ fontVariationSettings: "'FILL' 1" }}>auto_stories</span>
                <div className="absolute -top-4 -right-4 w-24 h-24 bg-tertiary-container rounded-full flex items-center justify-center floating" style={{ animationDelay: "-1.5s" }}>
                  <span className="material-symbols-outlined text-[40px] text-on-tertiary-container">event</span>
                </div>
              </div>
            </div>
          </div>
        </section>

        {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 news and events...</p>
          </div>
        ) : (
          <>
            {/* Spotlight News Section */}
            {spotlightEvent && (
              <section className="px-4 md:px-8 py-16 bg-surface max-w-7xl mx-auto" id="featured">
                <div className="mb-12">
                  <h2 className="font-headline-lg text-headline-lg text-primary">Spotlight News</h2>
                </div>
                <div className="glass-card bg-white rounded-xl overflow-hidden shadow-xl border border-outline-variant/30 grid md:grid-cols-2 group">
                  <div className="relative h-64 md:h-auto overflow-hidden">
                    <img 
                      className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-700" 
                      src={spotlightEvent.image || "https://lh3.googleusercontent.com/aida-public/AB6AXuDPaNrSveAEX6qyaH1dprofTwqha-6IV5IsWajOauyJ-RXj69RuxkaHqqnHV8-B5FJu-F6vjyoidA3rhrplesnvCDWktoS5oAvqi1jWhTUsS256lGRbwe34_dB_ngXV6-5btQZYpv1XRrqjfFq8Yc8GQFku2jpBESfb6iUmqwl7KTgPqxKC5bn80Q7cExKIwgvDMo9LoPG_QDKpvvf-wMgDGw4HuNQVd29w02Qk6iPC6_ZL31_rGo7xLw"} 
                      alt={spotlightEvent.title} 
                    />
                    <div className="absolute top-6 left-6 bg-secondary-container text-on-secondary-container px-4 py-1 rounded-full font-label-md font-semibold">
                      Featured
                    </div>
                  </div>
                  <div className="p-8 md:p-12 flex flex-col justify-center space-y-6">
                    <div className="flex items-center gap-2 text-on-surface-variant text-label-md font-semibold">
                      <span className="material-symbols-outlined text-primary text-lg">calendar_today</span>
                      {new Date(spotlightEvent.date).toLocaleDateString(undefined, { month: 'long', day: 'numeric', year: 'numeric' })}
                    </div>
                    <h3 className="font-headline font-bold text-2xl md:text-3xl text-on-surface leading-tight">{spotlightEvent.title}</h3>
                    <p className="font-body-md text-body-md text-on-surface-variant leading-relaxed">
                      {spotlightEvent.description}
                    </p>
                  </div>
                </div>
              </section>
            )}

            {/* Latest News Cards */}
            <section className="px-4 md:px-8 py-16 max-w-7xl mx-auto">
              <div className="flex justify-between items-end mb-12">
                <h2 className="font-headline-lg text-headline-lg text-primary">Latest News</h2>
              </div>
              
              {newsList.length === 0 ? (
                <p className="text-center py-10 text-on-surface-variant">Check back soon for more news updates!</p>
              ) : (
                <div className="grid md:grid-cols-3 gap-8">
                  {newsList.map((news) => (
                    <div key={news._id} className="bg-surface-container-lowest rounded-lg overflow-hidden border border-outline-variant/30 hover:shadow-xl transition-all duration-300 group flex flex-col h-full">
                      <div className="h-48 overflow-hidden">
                        <img 
                          className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" 
                          src={news.image} 
                          alt={news.title} 
                        />
                      </div>
                      <div className="p-6 space-y-3 flex flex-col flex-grow">
                        <span className="text-label-sm font-semibold text-tertiary uppercase tracking-wider">{news.category}</span>
                        <h4 className="font-headline font-semibold text-lg text-on-surface leading-snug flex-grow">{news.title}</h4>
                        <p className="text-on-surface-variant text-body-md line-clamp-3 leading-relaxed">{news.description}</p>
                        <div className="pt-4 border-t border-outline-variant/20 flex justify-between items-center text-label-sm text-on-surface-variant">
                          <span>{new Date(news.date).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}</span>
                          <span className="material-symbols-outlined text-sm cursor-pointer hover:text-primary">share</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </section>

            {/* Calendar & Upcoming Events */}
            <section className="px-4 md:px-8 py-16 bg-surface-container-low" id="calendar">
              <div className="max-w-7xl mx-auto grid lg:grid-cols-2 gap-16">
                <div>
                  <h2 className="font-headline-lg text-headline-lg text-primary mb-12">Upcoming Events</h2>
                  
                  {timelineEvents.length === 0 ? (
                    <p className="text-on-surface-variant">No upcoming events listed at the moment.</p>
                  ) : (
                    <div className="space-y-8 relative before:content-[''] before:absolute before:left-[15px] before:top-0 before:h-full before:w-[2px] before:bg-primary/20">
                      {timelineEvents.map((evt) => (
                        <div key={evt._id} className="relative pl-12">
                          <div className="absolute left-0 top-1 w-8 h-8 rounded-full bg-primary flex items-center justify-center text-on-primary">
                            <span className="material-symbols-outlined text-sm">
                              {evt.category === 'Sports' ? 'sports_soccer' : 'groups'}
                            </span>
                          </div>
                          <div className="bg-surface-container-lowest p-6 rounded-lg shadow-sm border border-outline-variant/10 hover:shadow-md transition-shadow">
                            <span className="text-primary font-bold block mb-1">
                              {new Date(evt.date).toLocaleDateString(undefined, { month: 'long', day: 'numeric', year: 'numeric' })}
                            </span>
                            <h4 className="font-headline font-semibold text-lg text-on-surface">{evt.title}</h4>
                            <p className="text-on-surface-variant mt-2 text-body-md leading-relaxed">{evt.description}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                {/* Calendar View Placeholder */}
                <div className="bg-white p-8 rounded-xl shadow-lg border border-outline-variant/20">
                  <h3 className="font-headline font-bold text-xl text-primary mb-6">Academic Planner</h3>
                  <div className="border border-outline-variant/30 rounded-lg p-6 bg-surface-container-low text-center">
                    <span className="material-symbols-outlined text-5xl text-primary mb-3">calendar_month</span>
                    <p className="font-semibold text-on-surface mb-2">Academic Calendar 2024-25</p>
                    <p className="text-sm text-on-surface-variant mb-6">Plan your study terms, examinations, and whimsical vacation festivals.</p>
                    <button className="bg-primary text-on-primary px-8 py-3 rounded-full font-semibold shadow-md active:scale-95 transition-all text-sm">
                      Download PDF Calendar
                    </button>
                  </div>
                </div>
              </div>
            </section>
          </>
        )}
      </main>
      <Footer />
    </div>
  );
}
