import { Metadata } from 'next';
import Image from 'next/image';
import Link from 'next/link';
import { getEvents, getAssetUrl, Event } from '@/lib/directus';

export const metadata: Metadata = {
  title: 'Events',
  description: 'Upcoming exhibitions, workshops, and events with Katheryn Trenshaw',
};

// Force dynamic rendering to ensure fresh data from Directus
export const dynamic = 'force-dynamic';
export const revalidate = 0;

async function getEventsList(): Promise<{ upcoming: Event[]; past: Event[] }> {
  try {
    const allEvents = await getEvents();
    const upcoming = allEvents.filter((e) => e.status === 'published');
    const past = allEvents.filter((e) => e.status === 'past');

    return { upcoming, past };
  } catch (error) {
    console.error('Error fetching events:', error);
    return { upcoming: [], past: [] };
  }
}

function formatDateRange(start?: string, end?: string): string {
  if (!start) return '';

  const startDate = new Date(start);
  const options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  };

  if (!end) return startDate.toLocaleDateString('en-GB', options);

  const endDate = new Date(end);
  if (startDate.getMonth() === endDate.getMonth()) {
    return `${startDate.getDate()} - ${endDate.toLocaleDateString('en-GB', options)}`;
  }

  return `${startDate.toLocaleDateString('en-GB', options)} - ${endDate.toLocaleDateString('en-GB', options)}`;
}

function EventCard({ event }: { event: Event }) {
  const imageUrl = getAssetUrl(event.image, { width: 600, quality: 80, format: 'webp' });

  return (
    <article className="group">
      <div className="img-zoom relative aspect-[16/9] bg-gray-100">
        {event.image ? (
          <Image
            src={imageUrl}
            alt={event.title}
            fill
            className="object-cover"
            sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 33vw"
          />
        ) : (
          <div className="flex h-full items-center justify-center text-gray-400">
            <span className="text-sm">Event</span>
          </div>
        )}
      </div>
      <div className="mt-4">
        <p className="text-sm text-gray-500">
          {formatDateRange(event.start_date, event.end_date)}
        </p>
        <h3 className="mt-1 font-serif text-xl">{event.title}</h3>
        {event.location && (
          <p className="mt-1 text-sm text-gray-600">{event.location}</p>
        )}
        {event.description && (
          <div
            className="mt-2 text-sm text-gray-600 line-clamp-2"
            dangerouslySetInnerHTML={{ __html: event.description }}
          />
        )}
      </div>
    </article>
  );
}

export default async function EventsPage() {
  const { upcoming, past } = await getEventsList();

  return (
    <div className="min-h-screen bg-white pt-24">
      {/* Header */}
      <div className="border-b border-gray-200">
        <div className="mx-auto max-w-7xl px-4 py-16 text-center">
          <h1 className="font-serif text-4xl md:text-5xl">Events</h1>
          <p className="mt-4 text-gray-600">
            Exhibitions, workshops, and creative gatherings
          </p>
        </div>
      </div>

      <div className="mx-auto max-w-7xl px-4 py-12">
        {/* Upcoming Events */}
        <section>
          <h2 className="font-serif text-2xl border-b border-gray-200 pb-4">
            Upcoming Events
          </h2>
          {upcoming.length > 0 ? (
            <div className="mt-8 grid gap-8 md:grid-cols-2 lg:grid-cols-3">
              {upcoming.map((event) => (
                <EventCard key={event.id} event={event} />
              ))}
            </div>
          ) : (
            <div className="mt-8 py-12 text-center">
              <p className="text-gray-500">
                No upcoming events at the moment.
              </p>
              <p className="mt-2 text-sm text-gray-400">
                Subscribe to the newsletter to be notified of new events.
              </p>
            </div>
          )}
        </section>

        {/* Past Events */}
        {past.length > 0 && (
          <section className="mt-16">
            <h2 className="font-serif text-2xl border-b border-gray-200 pb-4">
              Past Events
            </h2>
            <div className="mt-8 grid gap-8 md:grid-cols-2 lg:grid-cols-3">
              {past.map((event) => (
                <EventCard key={event.id} event={event} />
              ))}
            </div>
          </section>
        )}
      </div>

      {/* CTA */}
      <div className="border-t border-gray-200 bg-gray-50">
        <div className="mx-auto max-w-7xl px-4 py-16 text-center">
          <h3 className="font-serif text-2xl">Want to Host an Event?</h3>
          <p className="mt-4 text-gray-600">
            Interested in hosting a workshop or exhibition? Get in touch.
          </p>
          <Link href="/contact" className="mt-6 inline-block btn btn-primary">
            Contact Us
          </Link>
        </div>
      </div>
    </div>
  );
}
