<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { getCachedImageUrl } from '../common/imageCache'

const props = defineProps<{ childId: string | number }>()
const emit = defineEmits(['close'])

interface Task {
  id: string
  name: string
  is_good: boolean
  points: number
  image_id?: string | null
  image_url?: string | null
}

const tasks = ref<Task[]>([])
const loading = ref(true)
const error = ref<string | null>(null)

const fetchTasks = async () => {
  loading.value = true
  error.value = null
  try {
    const resp = await fetch(`/api/child/${props.childId}/list-assignable-tasks`)
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
    const data = await resp.json()
    const taskList: Task[] = data.assignable_tasks || []

    // Fetch images for each task if image_id is present
    await Promise.all(
      taskList.map(async (task) => {
        if (task.image_id) {
          try {
            task.image_url = await getCachedImageUrl(task.image_id)
          } catch (e) {
            task.image_url = null
          }
        }
      }),
    )

    tasks.value = taskList
  } catch (err) {
    error.value = err instanceof Error ? err.message : 'Failed to fetch tasks'
  } finally {
    loading.value = false
  }
}

onMounted(fetchTasks)
watch(() => props.childId, fetchTasks)
</script>

<template>
  <div class="modal-backdrop">
    <div class="modal">
      <h3>Assign Tasks</h3>
      <div v-if="loading" class="loading">Loading tasks...</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <div v-else class="task-listbox">
        <div
          v-for="task in tasks"
          :key="task.id"
          class="task-list-item"
          :class="{ good: task.is_good, bad: !task.is_good }"
        >
          <img v-if="task.image_url" :src="task.image_url" alt="Task" class="task-image" />
          <span class="task-name">{{ task.name }}</span>
          <span class="task-points">
            {{ task.is_good ? task.points : '-' + task.points }} pts
          </span>
        </div>
      </div>
      <button class="close-btn" @click="emit('close')">Close</button>
    </div>
  </div>
</template>

<style scoped>
.modal-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.45);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1200;
}
.modal {
  background: #fff;
  color: #222;
  padding: 1.5rem 2rem;
  border-radius: 12px;
  min-width: 260px;
  max-width: 95vw;
  max-height: 90vh;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
  text-align: center;
  overflow-y: auto;
}
.task-listbox {
  max-height: 320px;
  min-width: 220px;
  overflow-y: auto;
  margin: 1.2rem 0;
  display: flex;
  flex-direction: column;
  gap: 0.7rem;
}
.task-list-item {
  display: flex;
  align-items: center;
  border: 2px solid #38c172;
  border-radius: 8px;
  padding: 0.6rem 1rem;
  background: #f8fafc;
  font-size: 1.05rem;
  font-weight: 500;
  transition: border 0.18s;
}
.task-list-item.bad {
  border-color: #e53e3e;
  background: #fff5f5;
}
.task-list-item.good {
  border-color: #38c172;
  background: #f0fff4;
}
.task-name {
  flex: 1;
  text-align: left;
}
.task-points {
  min-width: 60px;
  text-align: right;
  font-weight: 600;
}
.close-btn {
  margin-top: 1.2rem;
  background: #f3f3f3;
  color: #666;
  border: none;
  border-radius: 8px;
  padding: 0.5rem 1.1rem;
  font-weight: 600;
  cursor: pointer;
  font-size: 1rem;
}
.close-btn:hover {
  background: #e2e8f0;
}
.loading,
.error {
  margin: 1.2rem 0;
  color: #888;
}
.error {
  color: #e53e3e;
}
.task-image {
  width: 36px;
  height: 36px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 0.7rem;
  background: #eee;
  flex-shrink: 0;
}
</style>
