<template>
  <section class="section">
    <header class="is-flex mb-6">
      <h1 class="title is-2 mr-5 mb-0">Calendrier</h1>
      <span class="mr-3">Séances</span>
      <div class="tabs is-toggle is-small">
        <ul>
          <li :class="isPast ? 'is-active' : undefined">
            <a @click="changeView('past')">
              <span>passées</span>
            </a>
          </li>
          <li :class="isPast ? undefined : 'is-active'">
            <a @click="changeView('future')">
              <span>à venir</span>
            </a>
          </li>
        </ul>
      </div>
    </header>
    <MovieCardListPerMonth :films-by-month="filmsByMonth" />
    <Pagination
      :model-value="currentPage"
      :max="totalPages"
      @update:model-value="changePage"
    />
  </section>
</template>

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

useHead({ title: "Calendrier" })
const router = useRouter()
const route = useRoute()

const currentPage = ref<number>(parseInt(route.query?.page as string) || 1)
const totalPages = ref<number>(1)
const currentView = ref<string>((route.query?.view as string) || "future")
const isPast = computed<boolean>(() => currentView.value === "past")

const filmsByMonth = ref<FilmsByMonth[]>([])

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

async function changeView(newView: string) {
  await loadFilms(1, newView === "past")
  currentView.value = newView
  router.replace({ query: { view: newView } })
}

await loadFilms(currentPage.value, isPast.value)

async function loadFilms(page = 1, isPast = false) {
  const res = (
    await apiGet<PaginatedResponse<FilmsByMonth>>(`films/calendar/`, {
      period: isPast ? "past" : "future",
      page: page,
    })
  ).data.value
  filmsByMonth.value = res?.results || []
  totalPages.value = res?.totalPages || 1
  currentPage.value = res?.currentPage || 1
}
</script>

<style scoped lang="sass">
header
  align-items: center
</style>
