<script setup lang="ts">
import type { OrderingProps } from '~/composables/navigation/useOrdering'
import type { Album, PaginatedAlbumList } from '~/types'
import { type operations } from '~/generated/types.ts'
import type { RouteRecordName } from 'vue-router'
import type { OrderingField } from '~/store/ui'

import { computed, ref, watch, onMounted } from 'vue'
import { useRouteQuery } from '@vueuse/router'
import { useI18n } from 'vue-i18n'
import { syncRef } from '@vueuse/core'
import { sortedUniq } from 'lodash-es'
import { useStore } from '~/store'

import axios from 'axios'

import TagsSelector from '~/components/library/TagsSelector.vue'
import Pagination from '~/components/ui/Pagination.vue'
import Card from '~/components/ui/Card.vue'
import AlbumCard from '~/components/album/Card.vue'
import Layout from '~/components/ui/Layout.vue'
import Input from '~/components/ui/Input.vue'
import Alert from '~/components/ui/Alert.vue'
import Spacer from '~/components/ui/Spacer.vue'
import Pills from '~/components/ui/Pills.vue'
import Loader from '~/components/ui/Loader.vue'

import useSharedLabels from '~/composables/locale/useSharedLabels'
import useOrdering from '~/composables/navigation/useOrdering'
import useErrorHandler from '~/composables/useErrorHandler'
import usePage from '~/composables/navigation/usePage'
import useLogger from '~/composables/useLogger'

interface Props extends OrderingProps {
  scope?: 'me' | 'all'

  // TODO(wvffle): Remove after https://github.com/vuejs/core/pull/4512 is merged
  orderingConfigName?: RouteRecordName
}

const props = withDefaults(defineProps<Props>(), {
  scope: 'all',
  orderingConfigName: undefined
})

const page = usePage()

const tags = useRouteQuery<string[]>('tag', [])

const tagList = computed(() => ({
  current: tags.value,
  others: []
}))

const q = useRouteQuery('query', '')
const query = ref(q.value)
syncRef(q, query, { direction: 'ltr' })

const result = ref<PaginatedAlbumList>()

const orderingOptions: [OrderingField, keyof typeof sharedLabels.filters][] = [
  ['creation_date', 'creation_date'],
  ['title', 'album_title'],
  ['release_date', 'release_date']
]

const logger = useLogger()
const sharedLabels = useSharedLabels()

const { onOrderingUpdate, orderingString, paginateBy, ordering, orderingDirection } = useOrdering(props)

const isLoading = ref(false)
const fetchData = async () => {
  isLoading.value = true
  const params : operations['get_album_fetches_2']['parameters']['query'] = {
    scope: props.scope,
    page: page.value,
    page_size: paginateBy.value,
    q: query.value,
    // @ts-ignore
    ordering: orderingString.value,
    playable: true,
    tag: tags.value,
    include_channels: true,
    content_category: 'music'
  }

  const measureLoading = logger.time('Fetching albums')
  try {
    const response = await axios.get<PaginatedAlbumList>('albums/', {
      params,
      paramsSerializer: {
        indexes: null
      }
    })

    result.value = response.data
  } catch (error) {
    useErrorHandler(error as Error)
    result.value = undefined
  } finally {
    measureLoading()
    isLoading.value = false
  }
}

const store = useStore()
watch(() => store.state.moderation.lastUpdate, fetchData)
watch([page, tags, q, () => props.scope], fetchData)
fetchData()

const search = () => {
  page.value = 1
  q.value = query.value
}

onOrderingUpdate(() => {
  page.value = 1
  fetchData()
})

const { t } = useI18n()
const labels = computed(() => ({
  searchPlaceholder: t('components.library.Albums.placeholder.search'),
  title: t('components.library.Albums.title')
}))

const paginateOptions = computed(() => sortedUniq([12, 30, 50, paginateBy.value].sort((a, b) => a - b)))
</script>

<template>
    <Layout stack main v-title="labels.title">
      <h1>{{ t('components.library.Albums.header.browse') }}</h1>
      <Layout form flex
        :class="['ui', {'loading': isLoading}, 'form']"
        @submit.prevent="search"
      >
        <Input search
          id="album-search"
          v-model="query"
          name="search"
          :label="t('components.library.Albums.label.search')"
          autofocus
          :placeholder="labels.searchPlaceholder"
        >
        </Input>
        <Pills
          v-model="tagList"
          :label="t('components.library.Albums.label.tags')"
          style="max-width: 150px;"
        />
        <select
          id="album-ordering"
          :label="t('components.library.Albums.ordering.label')"
          v-model="ordering"
          class="dropdown"
        >
          <option
            v-for="(option, key) in orderingOptions"
            :key="key"
            :value="option[0]"
          >
            {{ sharedLabels.filters[option[1]] }}
          </option>
        </select>
        <select
          :label="t('components.library.Albums.ordering.direction.label')"
          id="album-ordering-direction"
          v-model="orderingDirection"
          class="dropdown"
        >
          <option value="+">
            {{ t('components.library.Albums.ordering.direction.ascending') }}
          </option>
          <option value="-">
            {{ t('components.library.Albums.ordering.direction.descending') }}
          </option>
        </select>
        <select
          :label="t('components.library.Albums.pagination.results')"
          id="album-results"
          v-model="paginateBy"
          class="dropdown"
        >
          <option
            v-for="opt in paginateOptions"
            :key="opt"
            :value="opt"
          >
            {{ opt }}
          </option>
        </select>
      </Layout>
      <Loader v-if="isLoading"/>
      <Spacer />
      <Layout grid
        v-if="result && result.results.length > 0"
        style="display:flex; flex-wrap:wrap; gap: 32px; margin-top:32px;"
      >
        <AlbumCard
          v-for="album in result.results"
          :key="album.id"
          :album="album"
        />
      </Layout>
      <Layout
        stack
        v-else-if="result && result.results.length === 0"
      >
        <Alert yellow>
          <i class="bi bi-disc" />
          {{ t('components.library.Albums.empty.noResults') }}
        </Alert>
        <Card
          v-if="store.state.auth.authenticated"
          :title="t('components.library.Albums.link.addMusic')"
          solid
          small
          primary
          @click="store.commit('ui/toggleModal', 'upload')"
          :aria-pressed="store.state.ui.modalsOpen.has('upload') || undefined"
        >
          <template #image>
            <i class="bi bi-upload" style="font-size: 100px; position: relative; top: 50px;" />
          </template>
        </Card>
      </Layout>
      <Spacer grow />
        <Pagination
          v-if="result && result.count > paginateBy"
          v-model:page="page"
          :pages="Math.ceil((result.count || 0)/paginateBy)"
        />
    </Layout>
</template>
