import React from 'react';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import dbConnect from '@/lib/db';
import Event from '@/models/Event';
import Link from 'next/link';
import { Calendar, Clock, MapPin, ArrowRight, ArrowLeft } from 'lucide-react';

export const revalidate = 60;

async function getEvents(page: number = 1) {
  try {
    await dbConnect();
    const limit = 20;
    const skip = (page - 1) * limit;
    const today = new Date();

    // Upcoming (Only 1)
    const upcoming = await (Event as any).findOne({ 
      status: 'published', 
      startDate: { $gte: today } 
    }).sort({ startDate: 1 }).lean();

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

    const totalPast = await (Event as any).countDocuments({ status: 'published', startDate: { $lt: today } });

    return {
      upcoming: upcoming ? JSON.parse(JSON.stringify(upcoming)) : null,
      past: JSON.parse(JSON.stringify(pastEvents)),
      totalPages: Math.ceil(totalPast / limit),
      currentPage: page
    };
  } catch (e) {
    return { upcoming: null, past: [], totalPages: 0, currentPage: 1 };
  }
}

export default async function EventsPage(props: { searchParams: Promise<{ page?: string }> }) {
  const searchParams = await props.searchParams;
  const page = Number(searchParams.page) || 1;
  const { upcoming, past, totalPages, currentPage } = await getEvents(page);

  return (
    <div className="min-h-screen flex flex-col">
      <Navbar />
      
      <main className="flex-grow bg-slate-50 dark:bg-slate-900">
        
        {/* Header */}
        <div className="bg-slate-900 py-12 text-center border-b border-slate-800">
             <h1 className="text-4xl font-bold text-white font-display mb-2">Events</h1>
             <p className="text-slate-400 text-base">Networking, Conferences, and Trade Missions</p>
        </div>

        {/* Upcoming Event - Full Width */}
        {upcoming && (
          <section className="bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-800">
            <div className="max-w-7xl mx-auto">
               <div className="flex flex-col md:flex-row">
                  <div className="md:w-3/5 h-[400px] md:h-[500px] relative">
                     <img 
                        src={upcoming.posterImage || upcoming.image} 
                        alt={upcoming.title}
                        className="w-full h-full object-cover"
                     />
                     <div className="absolute top-0 left-0 bg-primary text-white text-xs font-bold px-5 py-2 uppercase tracking-widest">
                       Next Event
                     </div>
                  </div>
                  <div className="md:w-2/5 p-8 md:p-12 flex flex-col justify-center bg-slate-900 text-white">
                      <div className="text-primary font-bold mb-2 text-sm uppercase">
                         {new Date(upcoming.startDate).toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}
                      </div>
                      <h2 className="text-3xl md:text-4xl font-bold mb-6 leading-tight">{upcoming.title}</h2>
                      <div className="space-y-3 mb-8 text-slate-300 text-base">
                         {upcoming.timeText && <div className="flex items-center gap-3"><Clock size={18} /> {upcoming.timeText}</div>}
                         {upcoming.locationText && <div className="flex items-center gap-3"><MapPin size={18} /> {upcoming.locationText}</div>}
                      </div>
                      <Link href={`/event/${upcoming.slug}`} className="bg-primary hover:bg-primary-dark text-white px-8 py-3.5 rounded-full font-bold w-fit transition flex items-center gap-2 text-sm">
                        Event Details <ArrowRight size={16} />
                      </Link>
                  </div>
               </div>
            </div>
          </section>
        )}

        {/* Past Events Grid */}
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
          <h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-8 border-l-4 border-primary pl-4">
            Past Events
          </h3>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            {past.map((event: any) => (
              <Link href={`/event/${event.slug}`} key={event._id} className="group block bg-white dark:bg-slate-800 rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition">
                <div className="h-48 overflow-hidden relative">
                  <img 
                    src={event.posterImage || event.image || 'https://via.placeholder.com/400'} 
                    alt={event.title} 
                    loading="lazy"
                    className="w-full h-full object-cover group-hover:scale-110 transition duration-500" 
                  />
                  <div className="absolute top-3 left-3 bg-slate-900/80 backdrop-blur text-white text-[10px] font-bold px-2 py-1 rounded">
                    {new Date(event.startDate).toLocaleDateString()}
                  </div>
                </div>
                <div className="p-4">
                  <h4 className="font-bold text-slate-900 dark:text-white line-clamp-2 group-hover:text-primary transition text-base leading-snug">{event.title}</h4>
                  <div className="flex items-center gap-2 text-xs text-slate-500 mt-2">
                     <MapPin size={12} /> {event.locationText || 'Location TBD'}
                  </div>
                </div>
              </Link>
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex justify-center mt-12 gap-3">
              {currentPage > 1 && (
                <Link href={`/events?page=${currentPage - 1}`} className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-slate-800 rounded-lg shadow-sm hover:bg-slate-100 text-sm font-medium transition">
                  <ArrowLeft size={16} /> Prev
                </Link>
              )}
              <span className="px-4 py-2 text-sm text-slate-500">Page {currentPage} of {totalPages}</span>
              {currentPage < totalPages && (
                <Link href={`/events?page=${currentPage + 1}`} className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-slate-800 rounded-lg shadow-sm hover:bg-slate-100 text-sm font-medium transition">
                  Next <ArrowRight size={16} />
                </Link>
              )}
            </div>
          )}
        </div>
      </main>

      <Footer />
    </div>
  );
}