<template>
  <div>
    <header>
      <PageNav />
    </header>
    <main>
      <IndexHero />
      <div class="bg-gray-200 pb-12">
        <div class="max-w-2xl mx-auto py-8 px-4 sm:px-6 lg:max-w-7xl lg:px-8">
          <p v-if="$fetchState.pending">Fetching videos...</p>
          <p v-else-if="$fetchState.error">An error occurred :(</p>
          <div v-else id="videolist">
            <VideosList :videos="videos" />
            <SimplePagination
              :prev-page-token="prevPageToken"
              :next-page-token="nextPageToken"
            />
          </div>
          <TwitterFeed />
        </div>
      </div>
    </main>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
const maxResults: number = 12

export default Vue.extend({
  name: 'IndexPage',

  data(): {
    videos: []
    prevPageToken: string
    nextPageToken: string
  } {
    return {
      videos: [],
      prevPageToken: '',
      nextPageToken: '',
    }
  },

  async fetch() {
    try {
      let requestUrl =
        'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails'
      requestUrl += `&maxResults=${maxResults}`
      requestUrl += `&playlistId=${process.env.NUXT_ENV_YOUTUBE_UPLOADS_PLAYLIST_ID}`
      requestUrl += `&key=${process.env.NUXT_ENV_YOUTUBE_API_KEY}`
      if (this.$route.query.pageToken)
        requestUrl += `&pageToken=${this.$route.query.pageToken}`

      const response = await fetch(requestUrl)
      const json = await response.json()

      this.prevPageToken = json.prevPageToken
      this.nextPageToken = json.nextPageToken
      this.videos = json.items
    } catch (error: any) {
      throw new Error(error)
    }
  },

  watch: {
    '$route.query': '$fetch',
  },

  fetchOnServer: true,
})
</script>
