import React from 'react';
import dbConnect from '@/lib/db';
import Event from '@/models/Event';
import Leader from '@/models/Leader';
import GalleryItem from '@/models/GalleryItem';
import Navbar from '@/components/Navbar';
import Hero from '@/components/Hero';
import About from '@/components/About';
import Leadership from '@/components/Leadership';
import Events from '@/components/Events';
import Membership from '@/components/Membership';
import { HomeOpportunityAreas, HomeGrowthJourney } from '@/components/HomeExtraSections';
import MiscSections, { EventMomentsSection, HallOfFameSection } from '@/components/MiscSections';
import Footer from '@/components/Footer';

// Fetch data on the server with fallback
async function getData() {
  try {
    const db = await dbConnect();
    if (!db) throw new Error("No Database Connection");

    // 1. Fetch Top 6 Leaders (Sorted)
    const leaders = await (Leader as any).find({ status: 'published' })
      .sort({ order: 1 })
      .limit(6)
      .lean();

    const today = new Date();

    // 2. Fetch 1 Upcoming Event
    const upcomingEvents = await (Event as any).find({
      status: 'published',
      startDate: { $gte: today }
    }).sort({ startDate: 1 }).limit(1).lean();

    // 3. Fetch Last 4 Past Events
    const pastEvents = await (Event as any).find({
      status: 'published',
      startDate: { $lt: today }
    }).sort({ startDate: -1 }).limit(4).lean();

    // 4. Fetch latest gallery album and take up to 20 images for homepage
    const latestGallery = await (GalleryItem as any).findOne({ status: 'published' })
      .sort({ order: -1, createdAt: -1 })
      .lean();

    const homepageGalleryImages = latestGallery
      ? ((latestGallery as any).images && (latestGallery as any).images.length > 0
        ? (latestGallery as any).images.slice(0, 20).map((url: string) => ({ imageUrl: url, title: (latestGallery as any).name || (latestGallery as any).title || 'Gallery' }))
        : ((latestGallery as any).imageUrl ? [{ imageUrl: (latestGallery as any).imageUrl, title: (latestGallery as any).name || (latestGallery as any).title || 'Gallery' }] : []))
      : [];

    return {
      leaders: JSON.parse(JSON.stringify(leaders)),
      upcoming: upcomingEvents.length > 0 ? JSON.parse(JSON.stringify(upcomingEvents[0])) : null,
      past: JSON.parse(JSON.stringify(pastEvents)),
      gallery: JSON.parse(JSON.stringify(homepageGalleryImages))
    };

  } catch (error) {
    console.warn("Database connection failed or missing.");
    return { leaders: [], upcoming: null, past: [], gallery: [] };
  }
}

export const revalidate = 60;

export default async function Home() {
  const data = await getData();

  return (
    <div className="min-h-screen flex flex-col">
      <Navbar />
      <main className="flex-grow">
        <Hero />
        <About />
        <Leadership leaders={data.leaders} />
        <HomeGrowthJourney />
        <Events upcoming={data.upcoming} past={data.past} />

        <HomeOpportunityAreas />
        <EventMomentsSection galleryItems={data.gallery} />
        <Membership />
        <HallOfFameSection />
        <MiscSections />
      </main>
      <Footer />
    </div>
  );
}
