import { Metadata, ResolvingMetadata } from "next";
import { notFound } from "next/navigation";
import { getClient } from "@/app/client";
import { ImageSliderBlock } 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 } from "@/gql";
import { VenueFragment } from "@/gql/graphql";
import { getSeoMetadata } from "@/lib/seo";

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

type Params = Promise<{ slug: string }>;

export async function generateMetadata(
  { params }: { params: Params },
  parent: ResolvingMetadata
): Promise<Metadata | null> {
  const { slug } = await params;
  const { data, error } = await getClient().query(venueBySlugQuery, {
    slug,
  });

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.venue) {
    return null;
  }

  const venue = data.venue as VenueFragment;
  const metadata = await getSeoMetadata(venue, parent);
  return metadata;
}

export async function generateStaticParams() {
  const allVenueSlugsQuery = graphql(`
    query allVenueSlugs {
      pages(contentType: "venues.VenuePage", limit: 100) {
        id
        slug
      }
    }
  `);
  const { data, error } = await getClient().query(allVenueSlugsQuery, {});

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.pages) {
    throw new Error(
      "Failed to generate static params for subpages of /lokaler"
    );
  }

  return data.pages.map((page: any) => ({
    slug: page.slug,
  }));
}

export default async function Page({ params }: { params: Params }) {
  const { slug } = await params;
  const { data, error } = await getClient().query(venueBySlugQuery, {
    slug,
  });

  if (error) {
    throw new Error(error.message);
  }
  if (!data?.venue) {
    return notFound();
  }

  const venue = data.venue as VenueFragment;
  const featuredImage: any = venue.featuredImage;

  return (
    <main className="site-main" id="main">
      {venue.images && venue.images.length !== 0 && (
        <ImageSliderBlock block={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>
  );
}
