<template>
  <dialog
      ref="modal"
      closedby="any"
  >
    <form method="dialog">
      <header class="flex-row padding">
        {{ currentCardIndex! > -1 ? 'Bearbeiten' : 'Hinzufügen'}}
        <PpButton class="round text">
          <Icon name="uil:times" mode="svg" />
        </PpButton>
      </header>
      <main v-if="currentCard">
        <div class="padding flex-col">
          <div class="flex-row gap-default">
            <PpFormInput v-model="currentCard.name" label="Name" id="card_name" />
            <PpFormInput v-model="currentCard.price" label="Preis" id="card_price" />
          </div>
          <div class="flex-row gap-default">
            <PpFormInput v-model="currentCard.roles" label="Rollen" id="card_roles" />
            <PpFormInput v-model="currentCard.sheets" label="Blätter" id="card_sheets" />
            <PpFormInput v-model="currentCard.layers" label="Lagen" id="card_layers" />
          </div>
        </div>
      </main>
      <footer class="flex-row padding">
        <PpButton class="danger text">
          <span>Abbrechen</span>
        </PpButton>
        <PpButton class="raised" @click="updateCard()">
          <span>{{ currentCardIndex! > -1 ? 'Bearbeiten' : 'Hinzufügen'}}</span>
        </PpButton>
      </footer>
    </form>
  </dialog>
  <section class="content flex-col">
    <aside class="filter-bar">
      <PpButtonGroup
        :buttons="filterButtons"
        @click="sort"
      />
    </aside>
    <div class="pc-wrapper flex-col" role="list">
      <PpPriceCard
        v-for="(card, index) in cards"
        :key="card.uuid"
        :deletable="cards.length > 1"
        :card="card"
        @update="openModal(index)"
        @remove="removeCard(index)"
      />
    </div>
  </section>
  <PpToolbar>
    <PpButton class="mini-button text-white" @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" @click="openModal()">
      <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'

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

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

const cards = useState('cards', () => [
  createCard(crypto.randomUUID()),
])

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

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

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

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

const openModal = (index ?: number) => {
  modal.value?.showModal()
  if (index !== undefined && index > -1) {
    currentCardIndex.value = index
    currentCard.value = { ...cards.value[index]! }
    return
  }

  currentCardIndex.value = -1
  currentCard.value = createCard(crypto.randomUUID())
}

const updateLocalStorage = () => {
  localStorage.setItem('cards', JSON.stringify(cards.value))
  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 = card.price / card.roles
  const pps = (ppr / card.sheets) * 10
  const ppl = (pps / card.layers) * 10

  return { ppr, pps, ppl }
}

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