<template>
  <div class="chore-view">
    <MessageBlock v-if="countRef === 0" message="No chores">
      <span> <button class="round-btn" @click="create">Create</button> a chore </span>
    </MessageBlock>

    <ItemList
      v-else
      ref="listRef"
      fetchUrl="/api/chore/list"
      itemKey="tasks"
      :itemFields="TASK_FIELDS"
      imageField="image_id"
      deletable
      @clicked="(item: Task) => $router.push({ name: 'EditChore', params: { id: item.id } })"
      @delete="confirmDelete"
      @loading-complete="(count) => (countRef = count)"
      :getItemClass="() => ({ good: true })"
    >
      <template #item="{ item }">
        <img v-if="item.image_url" :src="item.image_url" />
        <span class="name">{{ item.name }}</span>
        <span class="value">{{ item.points }} pts</span>
      </template>
    </ItemList>

    <FloatingActionButton aria-label="Create Chore" @click="create" />

    <DeleteModal
      :show="showConfirm"
      message="Are you sure you want to delete this chore?"
      @confirm="deleteItem"
      @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 FloatingActionButton from '../shared/FloatingActionButton.vue'
import DeleteModal from '../shared/DeleteModal.vue'
import type { Task } from '@/common/models'
import { TASK_FIELDS } from '@/common/models'
import { eventBus } from '@/common/eventBus'

const $router = useRouter()
const showConfirm = ref(false)
const itemToDelete = ref<string | null>(null)
const listRef = ref()
const countRef = ref<number>(-1)

function handleModified() {
  listRef.value?.refresh()
}

onMounted(() => {
  eventBus.on('task_modified', handleModified)
})

onUnmounted(() => {
  eventBus.off('task_modified', handleModified)
})

function confirmDelete(id: string) {
  itemToDelete.value = id
  showConfirm.value = true
}

const deleteItem = async () => {
  const id =
    typeof itemToDelete.value === 'object' && itemToDelete.value !== null
      ? (itemToDelete.value as any).id
      : itemToDelete.value
  if (!id) return
  try {
    const resp = await fetch(`/api/chore/${id}`, { method: 'DELETE' })
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
  } catch (err) {
    console.error('Failed to delete chore:', err)
  } finally {
    showConfirm.value = false
    itemToDelete.value = null
  }
}

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

<style scoped>
.chore-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(.good) {
  border-color: var(--list-item-border-good);
  background: var(--list-item-bg-good);
}
</style>
