<template>
  <div class="d-flex flex-row">
    <v-text-field
      class="filter flex-1-0"
      placeholder="Filter by Name"
      v-model="filterValue"
    ></v-text-field>
  </div>
  <v-data-table-server
    :headers="headers"
    :items="games"
    :items-length="count"
    v-model:items-per-page="resultsPerPage"
    v-model:page="pageValue"
    v-model:sort-by="sortValue"
    @update:options="loadData"
  >
    <template v-slot:item.id="{ item }">
      <a v-bind:href="`/#/games/${item.id}`">{{ item.id }}</a>
    </template>
    <template v-slot:item.title="{ item }">
      <a v-bind:href="`/#/games/${item.id}`">{{ item.title }}</a>
    </template>
    <template v-slot:item.postdate="{ item }">
      {{ new Date(item.postdate * 1000).toISOString().split('T')[0] }}
    </template>

    <template #bottom></template>
  </v-data-table-server>
  <v-pagination v-model:model-value="pageValue" :length="pageCount"></v-pagination>
</template>

<style>
.filter {
  margin-top: 10px;
  margin-left: 5px;
  margin-right: 5px;
  margin-bottom: 0px;
}
</style>

<script setup lang="ts">
import { Game } from '../types'
import GameTable from './GameTable.vue'
import { onBeforeMount, watch, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
// import { VDataTable } from 'vuetify/components'

type ReadonlyHeaders = VDataTable['$props']['headers']

const headers: ReadonlyHeaders = [
  { title: 'ID', align: 'start', sortable: true, key: 'id' },
  { title: 'Title', align: 'start', sortable: true, key: 'title' },
  { title: 'Status', align: 'start', sortable: true, key: 'status' },
  { title: 'Post Date', align: 'start', sortable: true, key: 'postdate' }
]

const route = useRoute()
const router = useRouter()

const games = ref<Game[]>([])
const pageCount = ref(1)
const resultsPerPage = ref(10)

const count = ref(0)

const pageValue = ref(1)
const filterValue = ref('')
const sortValue = ref([])

async function loadData({ page, itemsPerPage, sortBy }: any) {
  let sortString = 'id asc'
  if (sortBy[0]) {
    sortString = `${sortBy[0].key} ${sortBy[0].order}`
  }

  const response = await axios.post('/api/game', {
    page: `${page - 1}`,
    count: `${itemsPerPage}`,
    orderBy: sortString,
    filter: filterValue.value ? `title:"${filterValue.value}"` : ''
  })

  games.value = response.data.gameData
  pageCount.value = response.data.pageCount
  count.value = response.data.totalCount
  console.log('asdf')
  console.log(page)
  console.log(itemsPerPage)
  console.log(sortBy)
  router.replace({
    query: {
      page: pageValue.value,
      sort: sortString === 'id asc' ? '' : sortString,
      filter: filterValue.value
    }
  })
}

async function reloadData() {
  loadData({
    page: pageValue.value,
    itemsPerPage: 10,
    sortBy: sortValue.value
  })
}

watch(route, (newRoute, oldRoute) => {
  console.log('route')
  if (newRoute.query.page) {
    pageValue.value = Number(newRoute.query.page)
  }

  if (newRoute.query.sort) {
    sortValue.value = [
      {
        key: newRoute.query.sort.split(' ')[0],
        order: newRoute.query.sort.split(' ')[1]
      }
    ]
  }

  if (newRoute.query.filter) {
    filterValue.value = newRoute.query.filter.toString()
  }
})

let debounce: ReturnType<typeof setTimeout>
watch(filterValue, (newFilter: string, oldFilter: string) => {
  clearTimeout(debounce)
  debounce = setTimeout(() => {
    reloadData()
  }, 500)
})

onBeforeMount(async () => {
  // Initialize Filter
  if (!route.query.page) {
    pageValue.value = 1
  } else {
    pageValue.value = Number(route.query.page)
    count.value = route.query.page * 10
  }

  // Initialize Sort
  if (!route.query.sort) {
    sortValue.value = []
  } else {    
    sortValue.value = [
      {
        key: route.query.sort.split(' ')[0],
        order: route.query.sort.split(' ')[1]
      }
    ]
  }

  // Initialize Filter
  if (route.query.filter) {
    filterValue.value = route.query.filter.toString()
  }
})
</script>
