import { graphql } from "@/gql";
import { EventFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { EventDetails } from "@/components/events/EventDetails";
import { EventHeader } from "@/components/events/EventHeader";
import { BgPig } from "@/components/general/BgPig";
import { PageContent } from "@/components/general/PageContent";
import { RichText } from "@/components/general/RichText";
import { getEventPig } from "@/lib/event";

const eventBySlugQuery = graphql(`
  query eventBySlug($slug: String!) {
    event: page(contentType: "events.EventPage", slug: $slug) {
      ... on EventPage {
        ...Event
      }
    }
  }
`);

export type EventPageViewProps = { event: EventFragment };

export async function loadEventPageProps(args: {
  slug?: string;
  eventOverride?: EventFragment;
}): Promise<EventPageViewProps | null> {
  if (args.eventOverride) {
    return { event: args.eventOverride };
  }
  if (!args.slug) throw new Error("loadEventPageProps needs slug or eventOverride");
  const { data, error } = await getClient().query(eventBySlugQuery, {
    slug: args.slug,
  });
  if (error) throw new Error(error.message);
  const event = data?.event as EventFragment | undefined;
  if (!event) return null;
  return { event };
}

export function EventPageView({ event }: EventPageViewProps) {
  const eventPig = getEventPig(event);

  return (
    <>
      <main className="site-main" id="main">
        <EventHeader event={event} />
        <EventDetails event={event} />
        {event.lead && (
          <div className="lead event-lead">
            <RichText content={event.lead} />
          </div>
        )}
        <PageContent blocks={event.body} />
      </main>
      {eventPig && <BgPig type={eventPig} color="white" />}
    </>
  );
}
