import type { GetStaticPaths, GetStaticProps, InferGetStaticPropsType } from 'next'
import ErrorPage from 'next/error'

import { getGlobalFields } from '@/lib/api/globals'
import { getAllPageUris, getPageByUri } from '@/lib/api/pages'

import ThankYouPageTemplate from '@/components/templates/ThankYouPage'
import ParseContent from '@/components/parsers/ParseContent'
import Container from '@/components/shared/Container'

export default function Page({ page }: InferGetStaticPropsType<typeof getStaticProps>) {
  if (!page?.uri) {
    return <ErrorPage statusCode={404} />
  }

  const { title, content } = page

  switch (page.template.__typename) {
    case 'Template_ThankYou':
      return <ThankYouPageTemplate page={page} />
    default:
      return (
        <Container>
          <article>
            <h1 className="text-h2">{title}</h1>
            <ParseContent content={content} />

            <hr />

            <details>
              <summary>page</summary>
              <pre>{JSON.stringify(page, null, 2)}</pre>
            </details>
          </article>
        </Container>
      )
  }
}

export const getStaticProps: GetStaticProps = async ({ params, preview = false }) => {
  const uriParts = (params?.page || []) as string[]
  const uri = uriParts.join('/')

  const { globals } = await getGlobalFields(preview)

  try {
    const { page } = await getPageByUri(uri)

    if (!page) {
      return {
        notFound: true,
        revalidate: 10,
      }
    } else {
      return {
        props: {
          key: page.id || '',
          globals,
          page,
          preview,
        },
        revalidate: 10,
      }
    }
  } catch (error) {
    return {
      props: {
        globals,
        preview,
      },
      notFound: true,
      revalidate: 10,
    }
  }
}

export const getStaticPaths: GetStaticPaths = async () => {
  const pages = await getAllPageUris()

  // Array of page paths to exclude (because we have a custom page set up in the app)
  const excludedPaths = [
    '/',
    '/about-us/',
    '/accessories/',
    '/blog/',
    '/case-studies/',
    '/careers/',
    '/contact/',
    '/decorating-finishes/',
    '/design-tools/',
    '/faq/',
    '/find-a-rep/',
    '/get-a-quote/',
    '/glossary/',
    '/materials-finishes/',
    '/packaging/',
    '/packaging/corrugated/',
    '/packaging/ci-rigid-box/',
    '/packaging/folding-carton/',
    '/packaging/turned-edge/',
    '/presentation-materials/',
    '/presentation-materials/pocket-folders/',
    '/presentation-materials/binders/',
    '/privacy-policy/',
    '/projects/',
    '/request-a-sample/',
    '/sample-kits/',
    '/sample-kits/architectural-folders/',
    '/sample-kits/sample-boards/',
    '/sample-kits/strap-sets/',
    '/search-results/',
    '/sustainability/',
    '/working-with-us/',
  ]

  return {
    paths:
      pages
        .filter(node => Boolean(node.uri) && !excludedPaths.includes(node.uri))
        .map(node => ({
          params: { page: node.uri.split('/').filter(Boolean) },
        })) || [],
    fallback: 'blocking',
  }
}
