<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">
        <div class="content-text">
          <h1>Mit ProPapier Preise vergleichen und sparen</h1>
        </div>
        <aside class="filter-bar">
          <PpFormDropDown
            :elements="sortElements"
            :current="currentSortElement!"
            @click="setSortElement"
          />
          <PpFormToggleButton
            :icons="['uil:sort-amount-up', 'uil:sort-amount-down']"
            :current="currentSortDirection"
            @click="countSortDirection"
          />
        </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'
import type { DropDownElement } from '../../shared/DropDown'

const cards = useLocalStorage<Card[]>('cards', [])
const currentSort = useLocalStorage<number>('sort', 0)
const currentSortDirection = useLocalStorage<number>('sortDirection', 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 sortElements : DropDownElement[] = [
  {
    label: 'Rollen',
    value: 0,
  },
  {
    label: 'Blatt',
    value: 1,
  },
  {
    label: 'Lagen',
    value: 2,
  }
]
const currentSortElement = ref<DropDownElement>(sortElements[0]!)

const setSortElement = (element : DropDownElement) => {
  sort(element.value as number)
}

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 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

    if (currentSortDirection.value === 0) {
      return bCard[key] - aCard[key]
    }

    return aCard[key] - bCard[key]
  })
}

const sort = async (index : number = currentSort.value) => {
  currentSort.value = index
  currentSortElement.value = sortElements[index]!

  await nextTick()

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

const countSortDirection = () => {
  let newSortDirection = currentSortDirection.value + 1
  if (newSortDirection > 1) newSortDirection = 0

  currentSortDirection.value = newSortDirection
  sort()
}
</script>
