import { Fragment } from 'react'
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import { useCartQuery } from '../storefront/hooks'
import { GetStaticProps } from 'next'
import { storefront } from '../storefront/sdk-gen/sdk'
import {
  CollectionFragment,
  collectionFragment
} from '../storefront/sdk-gen/fragments'

type PageProps = {
  collections: Array<CollectionFragment>
}

export default function Home({ collections }: PageProps) {
  const { data } = useCartQuery({ createCartIfNotFound: true })

  return (
    <div className={styles.container}>
      <Head>
        <title>Next.js + Shopify example</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to <a href="https://nextjs.org/docs">Next.js!</a> +{' '}
          <a href="https://shopify.dev/docs/api/storefront">Shopify</a> example
        </h1>

        <ul>
          <h2>Collections</h2>
          {collections.map((collection) => (
            <li key={collection.id}>
              <a href={`#`}>{collection.title}</a>
            </li>
          ))}
        </ul>

        <ul>
          <h2>Products</h2>
          {collections.map((collection) => (
            <Fragment key={collection.id}>
              {collection.products.nodes.map((product) => {
                return (
                  <li key={product.id}>
                    <a href={'#'}>{product.title}</a>
                  </li>
                )
              })}
            </Fragment>
          ))}
        </ul>

        <div>
          <h2>Cart: </h2>
          <pre>{data ? JSON.stringify(data, null, 2) : 'null'}</pre>
        </div>
      </main>

      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by{' '}
          <span className={styles.logo}>
            <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
          </span>
        </a>
      </footer>
    </div>
  )
}

export const getStaticProps: GetStaticProps<PageProps> = async (context) => {
  const { collections } = await storefront.query({
    collections: {
      __args: { first: 250 },
      nodes: collectionFragment
    }
  })

  return {
    props: {
      collections: collections.nodes
    }
  }
}
