<template>
  <div class="reward-assign-view">
    <h2>Assign Rewards{{ childName ? ` for ${childName}` : '' }}</h2>
    <div class="reward-view">
      <MessageBlock v-if="rewardCountRef === 0" message="No rewards">
        <span> <button class="round-btn" @click="goToCreateReward">Create</button> a reward </span>
      </MessageBlock>
      <ItemList
        v-else
        ref="rewardListRef"
        :fetchUrl="`/api/child/${childId}/list-all-rewards`"
        itemKey="rewards"
        :itemFields="REWARD_FIELDS"
        imageField="image_id"
        selectable
        @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>
    </div>
    <div class="actions" v-if="rewardCountRef != 0">
      <button class="btn btn-secondary" @click="onCancel">Cancel</button>
      <button class="btn btn-primary" @click="onSubmit">Submit</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ItemList from '../shared/ItemList.vue'
import MessageBlock from '../shared/MessageBlock.vue'
import '@/assets/styles.css'
import { REWARD_FIELDS } from '@/common/models'

const route = useRoute()
const router = useRouter()
const childId = route.params.id
const childName = typeof route.query.name === 'string' ? route.query.name : ''

const rewardListRef = ref()
const rewardCountRef = ref(-1)

function goToCreateReward() {
  router.push({ name: 'CreateReward' })
}

async function onSubmit() {
  const selectedIds = rewardListRef.value?.selectedItems ?? []
  try {
    const resp = await fetch(`/api/child/${childId}/set-rewards`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ reward_ids: selectedIds }),
    })
    if (!resp.ok) throw new Error('Failed to update rewards')
    router.back()
  } catch (err) {
    alert('Failed to update rewards.')
  }
}

function onCancel() {
  router.back()
}
</script>

<style scoped>
.reward-assign-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1 1 auto;
  width: 100%;
  height: 100%;
  padding: 0;
  min-height: 0;
}
.reward-assign-view h2 {
  font-size: 1.15rem;
  color: var(--assign-heading-color);
  font-weight: 700;
  text-align: center;
  margin: 0.2rem;
}

.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);
}

.actions {
  display: flex;
  gap: 3rem;
  justify-content: center;
  margin-top: 0.5rem;
}
.actions button {
  padding: 1rem 2.2rem;
  border-radius: 12px;
  border: 0;
  cursor: pointer;
  font-weight: 700;
  font-size: 1.25rem;
  transition: background 0.18s;
  min-width: 120px;
}
</style>
