<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { getCachedImageUrl } from '../../common/imageCache'
import type { PendingReward, Event, ChildRewardRequestEventPayload } from '@/common/models'
import { eventBus } from '@/common/eventBus'
import '@/assets/list-shared.css'

const emit = defineEmits(['item-clicked'])

const loading = ref(true)
const error = ref<string | null>(null)
const notifications = ref<PendingReward[]>([])

const fetchNotifications = async () => {
  loading.value = true
  error.value = null
  try {
    const resp = await fetch('/api/pending-rewards')
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
    const data = await resp.json()
    const rewards: PendingReward[] = data.rewards || []

    // Fetch images for child and reward
    await Promise.all(
      rewards.map(async (item) => {
        if (item.child_image_id) {
          try {
            item.child_image_url = await getCachedImageUrl(item.child_image_id)
          } catch (e) {
            item.child_image_url = null
          }
        }
        if (item.reward_image_id) {
          try {
            item.reward_image_url = await getCachedImageUrl(item.reward_image_id)
          } catch (e) {
            item.reward_image_url = null
          }
        }
      }),
    )
    notifications.value = rewards
  } catch (err) {
    error.value = err instanceof Error ? err.message : 'Failed to fetch notifications'
    notifications.value = []
  } finally {
    loading.value = false
  }
}

function handleRewardRequest(event: Event) {
  const payload = event.payload as ChildRewardRequestEventPayload
  const childId = payload.child_id
  const rewardId = payload.reward_id
  // Todo: Have event carry more info to avoid full refresh
  fetchNotifications()
}

onMounted(async () => {
  eventBus.on('child_reward_request', handleRewardRequest)
  await fetchNotifications()
})

onUnmounted(() => {
  eventBus.off('child_reward_request', handleRewardRequest)
})

function handleItemClick(item: PendingReward) {
  emit('item-clicked', item)
}
</script>

<template>
  <div class="centered-list-container">
    <div v-if="loading" class="loading">Loading notifications...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else-if="notifications.length === 0" class="empty">No notifications</div>
    <div v-else class="listbox">
      <div v-for="(item, idx) in notifications" :key="item.id">
        <div class="list-item notification-centered" @click="handleItemClick(item)">
          <div class="child-info">
            <img
              v-if="item.child_image_url"
              :src="item.child_image_url"
              alt="Child"
              class="list-image"
            />
            <span class="child-name">{{ item.child_name }}</span>
          </div>
          <span class="requested-text">requested</span>
          <div class="reward-info">
            <span class="reward-name">{{ item.reward_name }}</span>
            <img
              v-if="item.reward_image_url"
              :src="item.reward_image_url"
              alt="Reward"
              class="list-image"
            />
          </div>
        </div>
        <div v-if="idx < notifications.length - 1" class="list-separator"></div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.centered-list-container {
  width: 100%;
  display: flex;
  justify-content: center;
}
.notification-centered {
  justify-content: center;
}
.child-info {
  display: flex;
  align-items: center;
  gap: 0.7rem;
}
.child-name {
  font-weight: 600;
  color: var(--dialog-child-name);
}
.reward-info {
  display: flex;
  align-items: center;
  gap: 0.7rem;
  margin-bottom: 0rem;
}
.reward-name {
  font-weight: 600;
  color: var(--notification-reward-name);
}
.requested-text {
  margin: 0 0.7rem;
  font-weight: 500;
  color: var(--dialog-message);
  font-size: 1.05rem;
  white-space: nowrap;
}
</style>
