<template>
  <section class="content flex-col">
    <aside class="filter-bar">
      <PpButtonGroup
        :buttons="filterButtons"
        @click="sort"
      />
    </aside>
    <div class="pc-wrapper flex-col" role="list">
      <p
        v-for="product in products"
        :key="product.sku"
      >
        {{ product.name }} - {{ product.price }}
      </p>
    </div>
  </section>
</template>

<script setup lang="ts">
import type { Card } from '../../shared/Card'
import type { Button } from '../../shared/ButtonGroup'
import type { Product } from '../../shared/db/Product'

const currentSort = ref(0)

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

const { data : products } = useFetch<Product[]>('/api/products')

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

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
  }
}
</script>
