<template>
  <div class="nuxt-page-wrapper flex-col">
    <ClientOnly>
      <PpDeleteDialog
        ref="deleteModal"
        :current-card-index="currentCardIndex"
        @delete="removeCard(currentCardIndex)"
      />
      <PpPriceCardDialog
          ref="modal"
          :current-card="currentCard"
          :current-card-index="currentCardIndex"
          @update="updateCard()"
      />
      <section class="content flex-col">
        <aside class="filter-bar">
          <button v-for="(button, index) in filterButtons" @click="() => sort(index)" :class="{ 'active': button.active }">
            {{ button.label }}
          </button>
        </aside>
        <div class="flex-col" role="list" v-if="cards.length">
          <PpPriceCard
            ref="priceCard"
            v-for="(card, index) in cards"
            :key="card.uuid"
            :deletable="cards.length > 1"
            :card="card"
            @update="openModal(false, index)"
            @remove="openDeleteModal()"
          />
        </div>
        <p class="info-text grow" v-else>
          Du hast noch keinerlei Einträge angelegt.
          <br />Aber das ist gar nicht schlimm!
          <br />Tippe einfach unten auf "+ Hinzufügen" und leg los.
        </p>
      </section>
      <PpToolbar>
        <PpButton class="mini-button text-white transparent" @click="openModal(true, -1)">
          <Icon class="icon" name="uil:plus" mode="svg" />
          <span>Hinzufügen</span>
        </PpButton>
      </PpToolbar>
    </ClientOnly>
  </div>
</template>

<script setup lang="ts">
import type { Card } from '../../shared/Card'
import type { Button } from '../../shared/ButtonGroup'
import { PpPriceCardDialog, PpDeleteDialog, PpPriceCard } from '#components'

const cards = useLocalStorage<Card[]>('cards', [])
const currentSort = useLocalStorage<number>('sort', 0)
const currentCard = ref<Card>()
const currentCardIndex = ref<number>(-1)
const modal = useTemplateRef<typeof PpPriceCardDialog>('modal')
const deleteModal = useTemplateRef<typeof PpDeleteDialog>('deleteModal')
const priceCards = useTemplateRef<(typeof PpPriceCard)[]>('priceCard')

const createCard = (uuid : string) : Card => ({
  uuid,
  name: '',
  price: '',
  roles: '',
  sheets: '',
  layers: '',
})


const addCard = (card : Card) => {
  cards.value.unshift({ ...card })
  sort()
}

const removeCard = (index : number) => {
  cards.value.splice(index, 1)
  sort()
}

const updateCard = () => {
  if (currentCardIndex.value === -1) {
    addCard(currentCard.value!)
    return
  }

  const newCard = { ...currentCard.value! }
  cards.value.splice(currentCardIndex.value, 1, newCard)
  sort()
}

const openModal = (createNew : boolean, index : number) => {
  if (createNew) {
    currentCardIndex.value = -1
    currentCard.value = createCard(randomUUID())
    modal.value?.$el.showModal()
    return
  }

  currentCardIndex.value = index
  currentCard.value = { ...cards.value[index]! }

  modal.value?.$el.showModal()
  return
}

const openDeleteModal = () => {
  deleteModal.value?.$el.showModal()
}

const filterButtons = ref<Button[]>([
  {
    label: 'Rollen',
    icon: 'uil:toilet-paper',
    active: currentSort.value === 0,
  },
  {
    label: 'Blatt',
    icon: 'uil:file-landscape',
    active: currentSort.value === 1,
  },
  {
    label: 'Lagen',
    icon: 'uil:layer-group',
    active: currentSort.value === 2,
  },
])

const sortBy = (key : 'ppr' | 'pps' | 'ppl') => {
  cards.value.sort((a, b) => {
    const aCard = priceCards.value?.find(card => card.uuid === a.uuid) || null
    const bCard = priceCards.value?.find(card => card.uuid === b.uuid) || null
    if (!aCard || !bCard) return 0
    return aCard[key] - bCard[key]
  })
}

const sort = async (index : number = currentSort.value) => {
  currentSort.value = index
  filterButtons.value.forEach(button => { button.active = false })
  filterButtons.value[index]!.active = true

  await nextTick()

  switch (index) {
    case 0: return sortBy('ppr')
    case 1: return sortBy('pps')
    case 2: return sortBy('ppl')
  }
}
</script>
