import { graphql } from "@/gql";
import { GenericFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { PageHeader } from "@/components/general/PageHeader";
import { PageContent } from "@/components/general/PageContent";
import { BgPig } from "@/components/general/BgPig";

const GenericFragmentDefinition = graphql(`
  fragment Generic on GenericPage {
    __typename
    id
    urlPath
    seoTitle
    searchDescription
    title
    lead
    pig
    body {
      ...Blocks
    }
  }
`);

const genericPageByUrlPathQuery = graphql(`
  query genericPageByUrl($urlPath: String!) {
    page: page(contentType: "generic.GenericPage", urlPath: $urlPath) {
      ... on GenericPage {
        ...Generic
      }
    }
  }
`);

export type GenericPageViewProps = { page: GenericFragment };

export async function loadGenericPageProps(args: {
  urlPath?: string;
  pageOverride?: GenericFragment;
}): Promise<GenericPageViewProps | null> {
  if (args.pageOverride) {
    return { page: args.pageOverride };
  }
  if (!args.urlPath) throw new Error("loadGenericPageProps needs urlPath or pageOverride");
  const { data, error } = await getClient().query(genericPageByUrlPathQuery, {
    urlPath: args.urlPath,
  });
  if (error) throw new Error(error.message);
  const page = data?.page as GenericFragment | undefined;
  if (!page) return null;
  return { page };
}

export function GenericPageView({ page }: GenericPageViewProps) {
  return (
    <>
      <main className="site-main" id="main">
        <PageHeader heading={page.title} lead={page.lead} />
        <PageContent blocks={page.body} />
      </main>
      {page.pig && <BgPig type={page.pig} color="white" />}
    </>
  );
}
