<template>
  <div class="notification-view">
    <MessageBlock v-if="notificationListCountRef === 0" message="No new notifications">
    </MessageBlock>

    <ItemList
      v-else
      :key="refreshKey"
      :fetchUrl="`/api/pending-confirmations`"
      itemKey="confirmations"
      :itemFields="PENDING_CONFIRMATION_FIELDS"
      :imageFields="['child_image_id', 'entity_image_id']"
      @clicked="handleNotificationClick"
      @loading-complete="(count) => (notificationListCountRef = count)"
    >
      <template #item="{ item }">
        <div class="notification-centered">
          <div class="child-info">
            <img v-if="item.child_image_url" :src="item.child_image_url" alt="Child" />
            <span>{{ item.child_name }}</span>
          </div>
          <span class="requested-text">{{
            item.entity_type === 'chore' || item.entity_type === 'routine'
              ? 'completed'
              : 'requested'
          }}</span>
          <div class="reward-info">
            <span>{{ item.entity_name }}</span>
            <img v-if="item.entity_image_url" :src="item.entity_image_url" alt="" />
          </div>
        </div>
      </template>
    </ItemList>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import ItemList from '../shared/ItemList.vue'
import MessageBlock from '../shared/MessageBlock.vue'
import { maybeShow as tutorialMaybeShow, tutorialReady } from '@/tutorial/controller'
import type {
  PendingConfirmation,
  Event,
  ChildRewardRequestEventPayload,
  ChildChoreConfirmationPayload,
} from '@/common/models'
import { PENDING_CONFIRMATION_FIELDS } from '@/common/models'
import { eventBus } from '@/common/eventBus'

const router = useRouter()

const notificationListCountRef = ref(-1)
const refreshKey = ref(0)

function handleNotificationClick(item: PendingConfirmation) {
  router.push({
    name: 'ParentView',
    params: { id: item.child_id },
    query: { scrollTo: item.entity_id, entityType: item.entity_type },
  })
}

function handleRewardRequest(event: Event) {
  const payload = event.payload as ChildRewardRequestEventPayload
  if (
    payload.operation === 'CREATED' ||
    payload.operation === 'CANCELLED' ||
    payload.operation === 'GRANTED'
  ) {
    notificationListCountRef.value = -1
    refreshKey.value++
  }
}

function handleChoreConfirmation(event: Event) {
  const payload = event.payload as ChildChoreConfirmationPayload
  if (
    payload.operation === 'CONFIRMED' ||
    payload.operation === 'APPROVED' ||
    payload.operation === 'REJECTED' ||
    payload.operation === 'CANCELLED' ||
    payload.operation === 'RESET'
  ) {
    notificationListCountRef.value = -1
    refreshKey.value++
  }
}

watch([notificationListCountRef, tutorialReady], ([count, ready]) => {
  if (ready && typeof count === 'number' && count > 0) {
    tutorialMaybeShow(
      'notification-click',
      () => document.querySelector('.notification-view .list-item') as HTMLElement | null,
    )
  }
})

onMounted(() => {
  eventBus.on('child_reward_request', handleRewardRequest)
  eventBus.on('child_chore_confirmation', handleChoreConfirmation)
})

onUnmounted(() => {
  eventBus.off('child_reward_request', handleRewardRequest)
  eventBus.off('child_chore_confirmation', handleChoreConfirmation)
})
</script>

<style scoped>
.notification-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1 1 auto;
  width: 100%;
  height: 100%;
  padding: 0;
  min-height: 0;
}
.notification-centered {
  display: flex;
  justify-content: center;
  margin-inline: auto;
  align-items: center;
  flex-wrap: wrap;
  gap: 0.2rem;
  max-width: 100%;
  overflow: hidden;
}
.child-info {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-weight: 600;
  color: var(--dialog-child-name);
  min-width: 0;
}

.child-info span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.reward-info {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  margin-bottom: 0rem;
  font-weight: 600;
  color: var(--notification-reward-name);
  min-width: 0;
}

.reward-info span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.reward-info img,
.child-info img {
  flex-shrink: 0;
}

.requested-text {
  margin: 0 0.4rem;
  font-weight: 500;
  color: var(--dialog-message);
  font-size: 1.05rem;
  white-space: nowrap;
  flex-shrink: 0;
}
</style>
