import dynamic from "next/dynamic";
import { VenueFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { ImageSliderBlockFragmentDefinition } from "@/components/blocks/ImageSliderBlock";
import { Breadcrumb } from "@/components/general/Breadcrumb";
import { PageContent } from "@/components/general/PageContent";
import { NeufMap } from "@/components/venues/NeufMap";
import { VenueInfo } from "@/components/venues/VenueInfo";
import { graphql, unmaskFragment } from "@/gql";

const ImageSliderBlock = dynamic(() =>
  import("@/components/blocks/ImageSliderBlock").then((m) => m.ImageSliderBlock)
);

const venueBySlugQuery = graphql(`
  query venueBySlug($slug: String!) {
    venue: page(contentType: "venues.VenuePage", slug: $slug) {
      ... on VenuePage {
        ...Venue
      }
    }
  }
`);

export type VenuePageViewProps = { venue: VenueFragment };

export async function loadVenuePageProps(args: {
  slug?: string;
  venueOverride?: VenueFragment;
}): Promise<VenuePageViewProps | null> {
  if (args.venueOverride) {
    return { venue: args.venueOverride };
  }
  if (!args.slug) throw new Error("loadVenuePageProps needs slug or venueOverride");
  const { data, error } = await getClient().query(venueBySlugQuery, {
    slug: args.slug,
  });
  if (error) throw new Error(error.message);
  const venue = data?.venue as VenueFragment | undefined;
  if (!venue) return null;
  return { venue };
}

export function VenuePageView({ venue }: VenuePageViewProps) {
  return (
    <main className="site-main" id="main">
      {venue.images?.[0]?.__typename === "ImageSliderBlock" && (
        <ImageSliderBlock
          block={unmaskFragment(
            ImageSliderBlockFragmentDefinition,
            venue.images[0]
          )}
          hero
        />
      )}
      <div className="page-header-small">
        <Breadcrumb link="/utleie" text="Lokale" />
        <h1 className="page-title">{venue.title}</h1>
      </div>
      <PageContent blocks={venue.body} />
      <VenueInfo venue={venue} />
      <NeufMap venueSlug={venue.slug} />
    </main>
  );
}
