import { graphql } from "@/gql";
import { AssociationFragment, AssociationIndexFragment } from "@/gql/graphql";
import { getClient } from "@/app/client";
import { AssociationList } from "@/components/associations/AssociationList";
import { PageHeader } from "@/components/general/PageHeader";
import { PageContent } from "@/components/general/PageContent";

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

const AssociationFragmentDefinition = graphql(`
  fragment Association on AssociationPage {
    __typename
    id
    slug
    title
    seoTitle
    searchDescription
    excerpt
    lead
    body {
      ...Blocks
    }
    logo {
      url
      width
      height
    }
    associationType
    websiteUrl
  }
`);

const allAssociationsQuery = graphql(`
  query allAssociations {
    index: associationIndex {
      ... on AssociationIndex {
        ...AssociationIndex
      }
    }
    associations: pages(
      contentType: "associations.AssociationPage"
      limit: 1000
    ) {
      ... on AssociationPage {
        ...Association
      }
    }
  }
`);

export type AssociationIndexViewProps = {
  index: AssociationIndexFragment;
  associations: AssociationFragment[];
};

export async function loadAssociationIndexProps(overrides?: {
  indexOverride?: AssociationIndexFragment;
}): Promise<AssociationIndexViewProps> {
  const { data, error } = await getClient().query(allAssociationsQuery, {});
  if (error) throw new Error(error.message);
  const index =
    overrides?.indexOverride ?? (data?.index as AssociationIndexFragment | undefined);
  if (!index) throw new Error("Failed to load /foreninger");
  const associations = (data?.associations ?? []) as AssociationFragment[];
  return { index, associations };
}

export function AssociationIndexView({
  index,
  associations,
}: AssociationIndexViewProps) {
  return (
    <main className="site-main" id="main">
      <PageHeader heading={index.title} lead={index.lead} />
      {index.body && <PageContent blocks={index.body} />}
      <AssociationList
        associations={associations}
        heading="Foreninger og utvalg"
      />
    </main>
  );
}
