<template>
  <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">
      <PpButtonGroup
        :buttons="filterButtons"
        @click="sort"
      />
    </aside>
    <div class="flex-col" role="list">
      <PpPriceCard
        v-for="(card, index) in cards"
        :key="card.uuid"
        :deletable="cards.length > 1"
        :card="card"
        @update="openModal(false, index)"
        @remove="openDeleteModal()"
      />
    </div>
  </section>
  <PpToolbar>
    <PpButton class="mini-button text-white transparent" @click="sort(currentSort)">
      <Icon class="icon" name="uil:refresh" mode="svg" />
      <span>Neu sortieren</span>
      <span
        class="dot"
        :class="{ visible : isDirty}"
        aria-hidden="true"
      />
    </PpButton>
    <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>
</template>

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

const currentSort = ref(0)
const isDirty = ref(false)
const currentCard = ref<Card>()
const currentCardIndex = ref<number>(-1)
const modal = useTemplateRef<typeof PpPriceCardDialog>('modal')
const deleteModal = useTemplateRef<typeof PpDeleteDialog>('deleteModal')

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

const cards = useState<Card[]>('cards', () => [
  createCard(randomUUID()),
])

const addCard = (card : Card) => {
  const price = calculate(card)
  cards.value.unshift({ ...card, ...price })
  isDirty.value = true
  updateLocalStorage()
}

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

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

  const price = calculate(currentCard.value!)
  const newCard = { ...currentCard.value!, ...price }
  cards.value.splice(currentCardIndex.value, 1, newCard)
  isDirty.value = true
  updateLocalStorage()
}

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 updateLocalStorage = () => {
  localStorage.setItem('cards', JSON.stringify(cards.value.map(card => {
    const { uuid, name, price, roles, sheets, layers } = card
    return { uuid, name, price, roles, sheets, layers }
  })))
  localStorage.setItem('sort', JSON.stringify(currentSort.value))
}

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

const sortBy = (key : 'ppr' | 'pps' | 'ppl') => {
  cards.value.sort((a : Card, b : Card) => a[key] - b[key])
}

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

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

  updateLocalStorage()
  isDirty.value = false
}

const calculate = (card : Card) => {
  const ppr = +replaceComma(card.price) / +card.roles
  const pps = (ppr / +card.sheets) * 100
  const ppl = (pps / +card.layers)

  return { ppr, pps, ppl }
}

onMounted(() => {
  const cardsFromStorage = JSON.parse(localStorage.getItem('cards') ?? '[]').map((card : Card) => ({ ...card, ...calculate(card) }))
  cards.value = cardsFromStorage.length !== 0 ? cardsFromStorage : cards.value
  const sortFromStorage = +JSON.parse(localStorage.getItem('sort') ?? '0')
  sort(sortFromStorage)
  filterButtons.value[sortFromStorage]!.active = true
})
</script>
