import { Suspense } from "react";
import { VenueFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { EventContainer } from "@/components/events/EventContainer";
import { PageHeader } from "@/components/general/PageHeader";
import {
  EventCategory,
  EventFragment,
  EventOrganizer,
  eventsOverviewQuery,
} from "@/lib/event";

export type EventIndexViewProps = {
  events: EventFragment[];
  eventCategories: EventCategory[];
  eventOrganizers: EventOrganizer[];
  venues: VenueFragment[];
};

export async function loadEventIndexProps(): Promise<EventIndexViewProps> {
  const { data, error } = await getClient().query(eventsOverviewQuery, {});
  if (error) throw new Error(error.message);
  if (
    !data?.index ||
    !data?.events?.futureEvents ||
    !data?.eventCategories ||
    !data?.eventOrganizers ||
    !data?.venues
  ) {
    throw new Error("Failed to load /arrangementer");
  }
  return {
    events: data.events.futureEvents as EventFragment[],
    eventCategories: data.eventCategories as EventCategory[],
    eventOrganizers: data.eventOrganizers as EventOrganizer[],
    venues: data.venues as VenueFragment[],
  };
}

export function EventIndexView({
  events,
  eventCategories,
  eventOrganizers,
  venues,
}: EventIndexViewProps) {
  return (
    <main className="site-main" id="main">
      <PageHeader heading="Dette skjer på Chateau Neuf" align="left" />
      <Suspense>
        <EventContainer
          events={events}
          eventCategories={eventCategories}
          eventOrganizers={eventOrganizers}
          venues={venues}
        />
      </Suspense>
    </main>
  );
}
