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

    <ItemList
      v-else
      ref="listRef"
      fetchUrl="/api/routine/list"
      itemKey="routines"
      :itemFields="ROUTINE_FIELDS"
      imageField="image_id"
      deletable
      @clicked="(item: Routine) => $router.push({ name: 'EditRoutine', 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 Routine" @click="create" />

    <DeleteModal
      :show="showConfirm"
      message="Are you sure you want to delete this routine?"
      @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 { Routine } from '@/common/models'
import { ROUTINE_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('routine_modified', handleModified)
})

onUnmounted(() => {
  eventBus.off('routine_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/routine/${id}`, { method: 'DELETE' })
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
  } catch (err) {
    console.error('Failed to delete routine:', err)
  } finally {
    showConfirm.value = false
    itemToDelete.value = null
  }
}

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

<style scoped>
.routine-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>
