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

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

export async function loadEventIndexProps(): Promise<EventIndexViewProps> {
  const { data, error } = await getClient().query(
    eventsOverviewQuery,
    {},
    cachedUntilOsloMidnight()
  );
  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 EventOverviewItemFragment[],
    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" />
      <EventContainer
        events={events}
        eventCategories={eventCategories}
        eventOrganizers={eventOrganizers}
        venues={venues}
      />
    </main>
  );
}
