<script setup lang="ts">
import type { Track, Album, Artist, Library, ArtistCredit } from '~/types'

import { momentFormat } from '~/utils/filters'
import { computed, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter, useRoute } from 'vue-router'
import { sum } from 'lodash-es'
import { useStore } from '~/store'
import { useQueue } from '~/composables/audio/queue'

import axios from 'axios'

import ArtistCreditLabel from '~/components/audio/ArtistCreditLabel.vue'
import TrackFavoriteIcon from '~/components/favorites/TrackFavoriteIcon.vue'
import PlayButton from '~/components/audio/PlayButton.vue'
import TagsList from '~/components/tags/List.vue'
import AlbumDropdown from './AlbumDropdown.vue'
import Layout from '~/components/ui/Layout.vue'
import Spacer from '~/components/ui/Spacer.vue'
import Loader from '~/components/ui/Loader.vue'
import Button from '~/components/ui/Button.vue'
import HumanDuration from '~/components/common/HumanDuration.vue'

import useErrorHandler from '~/composables/useErrorHandler'
import useLogger from '~/composables/useLogger'

interface Events {
  (e: 'deleted'): void
}

interface Props {
  id: number
}

const store = useStore()

const emit = defineEmits<Events>()
const props = defineProps<Props>()

const object = ref<Album | null>(null)
const artist = ref<Artist | null>(null)
const artistCredit = ref([] as ArtistCredit[])
const libraries = ref([] as Library[])
const paginateBy = ref(50)

const totalTracks = computed(() => object.value?.tracks_count ?? 0)
const isChannel = computed(() => {
  return artistCredit.value.some(ac => ac.artist.channel)
})
const isAlbum = computed(() => {
  return artistCredit.value.some(ac => ac.artist.content_category === 'music')
})
const isSerie = computed(() => {
  return artistCredit.value.some(ac => ac.artist.content_category === 'podcast')
})

const totalDuration = computed(() => sum((object.value?.tracks ?? []).map(track => track.uploads[0]?.duration ?? 0)))
const publicLibraries = computed(() => libraries.value?.filter(library => library.privacy_level === 'everyone') ?? [])

const logger = useLogger()

const { t } = useI18n()

const labels = computed(() => ({
  title: t('components.library.AlbumBase.title'),
  shuffle: t('components.audio.Player.label.shuffleQueue')
}))

const {
  isShuffled,
  shuffle,
} = useQueue()

const isLoading = ref(false)
const fetchData = async () => {
  isLoading.value = true

  const albumResponse = await axios.get(`albums/${props.id}/`, { params: { refresh: 'true' } })

  artistCredit.value = albumResponse.data.artist_credit

  const artistResponse = await axios.get(`artists/${albumResponse.data.artist_credit[0].artist.id}/`)

  artist.value = artistResponse.data
  if (artist.value?.channel) {
    artist.value.channel.artist = artist.value
  }

  object.value = albumResponse.data
  if (object.value) {
    object.value.tracks = []
  }

  fetchTracks()
  isLoading.value = false
}

const tracks = reactive([] as Track[])
watch(tracks, (tracks) => {
  if (object.value) {
    object.value.tracks = tracks
  }
})

const isLoadingTracks = ref(false)
const fetchTracks = async () => {
  if (isLoadingTracks.value) return
  isLoadingTracks.value = true
  tracks.length = 0
  let url = 'tracks/'
  try {
    while (url) {
      const response = await axios.get(url, {
        params: {
          ordering: 'disc_number,position',
          album: props.id,
          page_size: paginateBy.value,
          include_channels: true
        }
      })

      url = response.data.next
      tracks.push(...response.data.results)
    }
  } catch (error) {
    logger.error(error)
  } finally {
    isLoadingTracks.value = false
  }
}

watch(() => props.id, fetchData, { immediate: true })

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

const remove = async () => {
  isLoading.value = true
  try {
    await axios.delete(`albums/${object.value?.id}`)
    emit('deleted')
    router.push({ name: 'library.artists.detail', params: { id: artist.value?.id } })
  } catch (error) {
    useErrorHandler(error as Error)
  }

  isLoading.value = false
}
</script>

<template>
  <Layout stack main>
    <Loader
      v-if="isLoading"
      v-title="labels.title"
    />
    <template v-if="object">
      <Layout flex>
        <img
          v-if="object.cover && object.cover.urls.original"
          v-lazy="store.getters['instance/absoluteUrl'](object.cover.urls.medium_square_crop)"
          alt=""
          class="channel-image"
        >
        <img
          v-else-if="object.artist_credit && object.artist_credit[0] && object.artist_credit[0].artist.cover"
          alt=""
          class="channel-image"
          :src="object.artist_credit[0].artist.cover.urls.medium_square_crop"
          />
        <img
          v-else
          alt=""
          class="channel-image"
          src="../../assets/audio/default-cover.png"
        >
        <!-- ({target}) => target -->
        <!-- Header (TODO: Put into Header component) -->
          <Layout stack style="flex: 1; gap: 8px;">
            <h1>{{ object.title }}</h1>
            <artist-credit-label
              v-if="artistCredit"
              :artist-credit="artistCredit"
            />
            <!-- Metadata: -->
            <div class="meta">
              <template v-if="object.release_date">
                {{ momentFormat(new Date(object.release_date ?? '1970-01-01'), 'Y') }}
                <i class="bi bi-dot" />
              </template>
              <template v-if="totalTracks > 0">
                <span v-if="isSerie">
                  {{ t('components.library.AlbumBase.meta.episodes', totalTracks) }}
                </span>
                <span v-else>
                  {{ t('components.library.AlbumBase.meta.tracks', totalTracks) }}
                </span>
              </template>
              <i v-if="totalDuration > 0" class="bi bi-dot" />
              <human-duration
                v-if="totalDuration > 0"
                :duration="totalDuration"
              />
              <i v-if="object.tags && object.tags.length > 0" class="bi bi-dot" />
              <!--TODO: License -->
              <TagsList
                v-if="object.tags && object.tags.length > 0"
                :tags="object.tags"
              />
            </div>
            <Layout flex>
              <rendered-description
                v-if="object.description"
                :content="object.description"
                :can-update="true"
              />
            </Layout>
            <Layout flex>
              <PlayButton
                class="vibrant"
                split
                :tracks="object.tracks"
                :is-playable="object.is_playable"
              />
              <Button
                primary
                icon="bi-shuffle"
                :disabled="object.tracks.length < 2"
                :aria-label="labels.shuffle"
                @click.prevent.stop="shuffle()"
              >
                {{ labels.shuffle }}
              </Button>
              <Spacer h grow />
              <TrackFavoriteIcon v-if="store.state.auth.authenticated" :album="object" />
              <TrackPlaylistIcon v-if="store.state.auth.authenticated" :album="object" />
                 <!-- TODO: Share Button -->
              <album-dropdown
                :object="object"
                :public-libraries="publicLibraries"
                :is-loading="isLoading"
                :is-album="isAlbum"
                :is-serie="isSerie"
                :is-channel="isChannel"
                :artist-credit="artistCredit"
                @remove="remove"
              />
            </Layout>
          </Layout>
      </Layout>

    <div style="flex 1;">
      <router-view
        v-if="object"
        :key="route.fullPath"
        :paginate-by="paginateBy"
        :total-tracks="totalTracks"
        :is-serie="isSerie"
        :artist-credit="artistCredit"
        :object="object"
        :is-loading-tracks="isLoadingTracks"
        object-type="album"
        @libraries-loaded="libraries = $event"
      />
    </div>
    </template>
  </Layout>
</template>

<style scopen>
  .meta {
    line-height: 48px;
  }
</style>
