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

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

const VenueFragmentDefinition = graphql(`
  fragment Venue on VenuePage {
    __typename
    id
    slug
    title
    seoTitle
    searchDescription
    images {
      __typename
      ... on ImageSliderBlock {
        ...ImageSliderBlock
      }
    }
    body {
      ...Blocks
    }
    featuredImage {
      ...Image
    }
    showAsBookable
    showInOverview
    floor
    preposition
    usedFor
    techSpecsUrl
    capabilityAudio
    capabilityAudioVideo
    capabilityBar
    capabilityLighting
    capacityLegal
    capacityStanding
    capacitySitting
  }
`);

const venueIndexQuery = graphql(`
  query venueIndex {
    index: venueIndex {
      ... on VenueIndex {
        ...VenueIndex
      }
    }
    venues: pages(contentType: "venues.VenuePage", limit: 100) {
      ... on VenuePage {
        ...Venue
      }
    }
  }
`);

export type VenueIndexViewProps = {
  index: VenueIndexFragment;
  venues: VenueFragment[];
};

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

export function VenueIndexView({ index, venues }: VenueIndexViewProps) {
  const visibleVenues = venues.filter((x) => x.showInOverview);

  return (
    <main className="site-main" id="main">
      <PageHeader heading={index.title} lead={index.lead} />
      <PageContent blocks={index.body} />
      <VenueList venues={visibleVenues} />
    </main>
  );
}
