<template>
  <div class="reward-view">
    <MessageBlock v-if="rewardCountRef === 0" message="No rewards">
      <span> <button class="round-btn" @click="createReward">Create</button> a reward </span>
    </MessageBlock>

    <ItemList
      v-else
      ref="rewardListRef"
      fetchUrl="/api/reward/list"
      itemKey="rewards"
      :itemFields="REWARD_FIELDS"
      imageField="image_id"
      deletable
      @clicked="(reward: Reward) => $router.push({ name: 'EditReward', params: { id: reward.id } })"
      @delete="(reward: Reward) => confirmDeleteReward(reward.id)"
      @loading-complete="(count) => (rewardCountRef = count)"
      :getItemClass="(item) => `reward`"
    >
      <template #item="{ item }">
        <img v-if="item.image_url" :src="item.image_url" />
        <span class="name">{{ item.name }}</span>
        <span class="value">{{ item.cost }} pts</span>
      </template>
    </ItemList>

    <FloatingActionButton aria-label="Create Reward" @click="createReward" />

    <DeleteModal
      :show="showConfirm"
      message="Are you sure you want to delete this reward?"
      @confirm="deleteReward"
      @cancel="showConfirm = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import ItemList from '../shared/ItemList.vue'
import MessageBlock from '@/components/shared/MessageBlock.vue'
//import '@/assets/button-shared.css'
import FloatingActionButton from '../shared/FloatingActionButton.vue'
import DeleteModal from '../shared/DeleteModal.vue'
import type { Reward } from '@/common/models'
import { REWARD_FIELDS } from '@/common/models'

import { eventBus } from '@/common/eventBus'

const $router = useRouter()

const showConfirm = ref(false)
const rewardToDelete = ref<string | null>(null)
const rewardListRef = ref<InstanceType<typeof ItemList> | null>(null)
const rewardCountRef = ref<number>(-1)

function handleRewardModified(event: any) {
  // Always refresh the reward list on any add, edit, or delete
  if (rewardListRef.value && typeof rewardListRef.value.refresh === 'function') {
    rewardListRef.value.refresh()
  }
}

onMounted(() => {
  eventBus.on('reward_modified', handleRewardModified)
})

onUnmounted(() => {
  eventBus.off('reward_modified', handleRewardModified)
})
function confirmDeleteReward(rewardId: string) {
  rewardToDelete.value = rewardId
  showConfirm.value = true
}

const deleteReward = async () => {
  const id = rewardToDelete.value
  if (!id) return
  try {
    const resp = await fetch(`/api/reward/${id}`, {
      method: 'DELETE',
    })
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
    // No need to refresh here; SSE will trigger refresh
  } catch (err) {
    console.error('Failed to delete reward:', err)
  } finally {
    showConfirm.value = false
    rewardToDelete.value = null
  }
}

const createReward = () => {
  $router.push({ name: 'CreateReward' })
}
</script>

<style scoped>
.reward-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1 1 auto;
  width: 100%;
  height: 100%;
  padding: 0;
  min-height: 0;
}

.name {
  flex: 1;
  text-align: left;
  font-weight: 600;
}

.value {
  min-width: 60px;
  text-align: right;
  font-weight: 600;
}

:deep(.reward) {
  border-color: var(--list-item-border-reward);
  background: var(--list-item-bg-reward);
}
</style>
