<template>
  <div class="deck-playlist">
    <div class="flex flex-col fixed right-0 top-0 z-50">
      <button @click="closeDatBox" v-if="uiStore.isBoxSelected"
        class="px-4 py-2 text-black hover:text-black bg-esyellow transition-colors z-50" aria-label="close the box">
        close
      </button>
    </div>
    <div class="controls flex justify-center z-50 relative">
      <button class="px-4 py-2 text-black hover:text-black bg-esyellow transition-colors" @click="toggleAllCards">
        {{ allCardsRevealed ? 'Hide All' : 'Reveal All' }}
      </button>
      <SearchInput @search="onSearch" />
      <SelectCardRank @change="onRankChange" />
      <SelectCardSuit @change="onSuitChange" />
    </div>
    <div ref="deck" class="deck flex flex-wrap justify-center gap-4" :class="{ 'pb-36': playerStore.currentTrack }">
      <card v-for="(track, i) in filteredTracks" :key="track.id" :track="track" :tabindex="i"
        :is-face-up="isCardRevealed(track.id)" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useDataStore } from '~/store/data'
import { useCardStore } from '~/store/card'
import { usePlayerStore } from '~/store/player'
import { useUiStore } from '~/store/ui'
import type { Box } from '~~/types/types'
import SelectCardSuit from '~/components/ui/SelectCardSuit.vue'
import SelectCardRank from '~/components/ui/SelectCardRank.vue'
import SearchInput from '~/components/ui/SearchInput.vue'

const props = defineProps<{
  box: Box
}>()

const cardStore = useCardStore()
const dataStore = useDataStore()
const playerStore = usePlayerStore()
const uiStore = useUiStore()

const deck = ref()
const tracks = computed(() => dataStore.getTracksByboxId(props.box.id))
const filteredTracks = ref(tracks.value)

// Variables réactives pour les filtres
const selectedSuit = ref('')
const selectedRank = ref('')
const searchQuery = ref('')

const isCardRevealed = (trackId: number) => cardStore.isCardRevealed(trackId)

// Vérifie si toutes les cartes sont révélées
const allCardsRevealed = computed(() => {
  return tracks.value.every(track => cardStore.isCardRevealed(track.id))
})

// Fonction pour basculer l'état de toutes les cartes
const toggleAllCards = () => {
  if (allCardsRevealed.value) {
    cardStore.hideAllCards(tracks.value)
  } else {
    cardStore.revealAllCards(tracks.value)
  }
}

const closeDatBox = () => {
  uiStore.closeBox()
}

const onSuitChange = (suit: string) => {
  selectedSuit.value = suit
  applyFilters()
}

const onRankChange = (rank: string) => {
  selectedRank.value = rank
  applyFilters()
}

const onSearch = (query: string) => {
  searchQuery.value = query
  applyFilters()
}

// Applique tous les filtres (couleur, rang et recherche)
const applyFilters = () => {
  let result = [...tracks.value]

  // Filtre par couleur
  if (selectedSuit.value) {
    result = result.filter(track => track.card?.suit === selectedSuit.value)
  }

  // Filtre par rang
  if (selectedRank.value) {
    result = result.filter(track => track.card?.rank === selectedRank.value)
  }

  // Filtre par recherche textuelle
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(track => {
      // Gestion du nom d'artiste (peut être un objet ou une chaîne)
      const artistName = typeof track.artist === 'object' ? track.artist?.name : String(track.artist || '')
      // Recherche dans le titre, l'artiste et l'année
      return (
        track.title?.toLowerCase().includes(query) ||
        artistName.toLowerCase().includes(query) ||
        String(track.year || '').includes(query)
      )
    })
  }

  filteredTracks.value = result
}
</script>
