<template>
  <main class="section">
    <h1 class="title">Liste des séances</h1>
    <ul class="list has-visible-pointer-controls">
      <li v-for="film of films" :key="film.id" class="list-item">
        <nuxt-link :to="`/admin/${film.id}`" class="list-item-content">
          <time v-if="film.projectionDate" :datetime="film.projectionDate">
            {{ new Date(film.projectionDate).toLocaleString() }}
          </time>
          <template v-else>À planifier</template>
          - {{ film.title }}
          <template v-if="film.director"> de {{ film.director }}</template>
        </nuxt-link>
        <div class="list-item-controls">
          <nuxt-link :to="`/admin/${film.id}/edition`" class="button">
            <span>Éditer</span>
          </nuxt-link>
        </div>
      </li>
    </ul>
    <Pagination
      :model-value="currentPage"
      :max="totalPages"
      @update:model-value="changePage"
    />
  </main>
</template>

<script setup lang="ts">
import { ShortFilm, PaginatedResponse } from "~/composables/types"

definePageMeta({ layout: "admin" })
useHead({ title: "Liste des séances" })
const route = useRoute()
const router = useRouter()

const currentPage = ref<number>(parseInt(route.query?.page as string) || 1)
const totalPages = ref<number>(1)

const films = reactive<ShortFilm[]>([])

async function changePage(newPage: number) {
  await loadFilms(newPage)
  router.replace({ query: { ...route.query, page: currentPage.value } })
}

await loadFilms(currentPage.value)

async function loadFilms(page = 1) {
  const res = (
    await apiGet<PaginatedResponse<ShortFilm>>(`admin/films/`, {
      page: page,
    })
  ).data.value
  Object.assign(films, res?.results || [])
  totalPages.value = res?.totalPages || 1
  currentPage.value = res?.currentPage || 1
}
</script>

<style lang="sass">
.list-item-content
  display: block
</style>
