import { graphql } from "@/gql";
import { VenueFragment, VenueRentalIndexFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { BgPig } from "@/components/general/BgPig";
import { PageContent } from "@/components/general/PageContent";
import { PageHeader } from "@/components/general/PageHeader";
import { VenueList } from "@/components/venues/VenueList";

const VenueRentalIndexDefinition = graphql(`
  fragment VenueRentalIndex on VenueRentalIndex {
    __typename
    title
    seoTitle
    searchDescription
    lead
    body {
      ...Blocks
    }
  }
`);

const venueRentalIndexQuery = graphql(`
  query venueRentalIndex {
    index: venueRentalIndex {
      ... on VenueRentalIndex {
        ...VenueRentalIndex
      }
    }
    venues: pages(contentType: "venues.VenuePage", limit: 100) {
      ... on VenuePage {
        ...Venue
      }
    }
  }
`);

export type VenueRentalIndexViewProps = {
  index: VenueRentalIndexFragment;
  venues: VenueFragment[];
};

export async function loadVenueRentalIndexProps(overrides?: {
  indexOverride?: VenueRentalIndexFragment;
}): Promise<VenueRentalIndexViewProps> {
  const { data, error } = await getClient().query(venueRentalIndexQuery, {});
  if (error) throw new Error(error.message);
  const index =
    overrides?.indexOverride ?? (data?.index as VenueRentalIndexFragment | undefined);
  if (!index) throw new Error("Failed to load /utleie");
  const venues = (data?.venues ?? []) as VenueFragment[];
  return { index, venues };
}

export function VenueRentalIndexView({
  index,
  venues,
}: VenueRentalIndexViewProps) {
  const bookableVenues = venues.filter((venue) => venue.showAsBookable);

  return (
    <>
      <main className="site-main" id="main">
        <PageHeader heading={index.title} lead={index.lead} />
        {index.body && <PageContent blocks={index.body} />}
        <VenueList venues={bookableVenues} heading="Våre lokaler" />
      </main>
      <BgPig type="key" />
    </>
  );
}
