<template>
  <div class="assign-view">
    <h2>Assign Routines{{ childName ? ` for ${childName}` : '' }}</h2>
    <div class="list-container">
      <MessageBlock v-if="routines.length === 0" message="No routines">
        <span> <button class="round-btn" @click="goToCreate">Create</button> a routine </span>
      </MessageBlock>
      <div v-else class="routine-selection">
        <div
          v-for="routine in routines"
          :key="routine.id"
          class="routine-item"
          @click="toggleRoutine(routine.id)"
        >
          <img v-if="routine.image_url" :src="routine.image_url" :alt="routine.name" />
          <span class="name">{{ routine.name }}</span>
          <span class="value">{{ routine.points }} pts</span>
          <input
            type="checkbox"
            v-model="selectedIds"
            :value="routine.id"
            :aria-label="`Select ${routine.name}`"
            @click.stop
          />
        </div>
      </div>
    </div>
    <div class="actions" v-if="routines.length > 0">
      <button class="btn btn-secondary" @click="onCancel">Cancel</button>
      <button class="btn btn-primary" @click="onSubmit" :disabled="isLoading">
        {{ isLoading ? 'Saving...' : 'Submit' }}
      </button>
    </div>

    <FloatingActionButton aria-label="Create Routine" @click="goToCreate" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { setChildRoutines } from '@/common/api'
import MessageBlock from '../shared/MessageBlock.vue'
import FloatingActionButton from '../shared/FloatingActionButton.vue'
import { getCachedImageUrl } from '@/common/imageCache'
import '@/assets/styles.css'
import type { Routine } from '@/common/models'

const route = useRoute()
const router = useRouter()
const childId = route.params.id as string
const childName = typeof route.query.name === 'string' ? route.query.name : ''
const routines = ref<Routine[]>([])
const selectedIds = ref<string[]>([])
const isLoading = ref(false)

onMounted(async () => {
  await fetchRoutines()
})

async function fetchRoutines() {
  try {
    // Fetch child to get currently assigned routines
    const childResp = await fetch(`/api/child/${childId}`)
    if (!childResp.ok) throw new Error('Failed to fetch child')
    const childData = await childResp.json()
    selectedIds.value = childData.routines || []

    // Fetch all routines and resolve images
    const routinesResp = await fetch('/api/routine/list')
    if (!routinesResp.ok) throw new Error('Failed to fetch routines')
    const routinesData = await routinesResp.json()
    const rawRoutines: Routine[] = routinesData.routines || []
    await Promise.all(
      rawRoutines.map(async (r: Routine) => {
        if (r.image_id) {
          try {
            r.image_url = await getCachedImageUrl(r.image_id)
          } catch {
            r.image_url = null
          }
        }
      }),
    )
    routines.value = rawRoutines
  } catch (error) {
    console.error('Failed to fetch routines:', error)
  }
}

function toggleRoutine(routineId: string) {
  const index = selectedIds.value.indexOf(routineId)
  if (index > -1) {
    selectedIds.value.splice(index, 1)
  } else {
    selectedIds.value.push(routineId)
  }
}

function goToCreate() {
  router.push({ name: 'CreateRoutine' })
}

async function onSubmit() {
  isLoading.value = true
  try {
    const resp = await setChildRoutines(childId, selectedIds.value)
    if (!resp.ok) throw new Error('Failed to update routines')
    router.back()
  } catch (error) {
    console.error('Failed to update routines:', error)
    alert('Failed to update routines.')
  } finally {
    isLoading.value = false
  }
}

function onCancel() {
  router.back()
}
</script>

<style scoped>
.assign-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1 1 auto;
  width: 100%;
  height: 100%;
  padding: 0;
  min-height: 0;
}

.assign-view h2 {
  font-size: 1.15rem;
  color: var(--assign-heading-color);
  font-weight: 700;
  text-align: center;
  margin: 0.2rem;
}

.list-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1 1 auto;
  width: 100%;
  height: 100%;
  padding: 0;
  min-height: 0;
}

.routine-selection {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  width: 100%;
  max-width: 500px;
}

.routine-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem 1rem;
  border: 2px solid var(--list-item-border-good);
  border-radius: 8px;
  background: var(--list-item-bg-good);
  cursor: pointer;
  transition:
    background 0.2s,
    border-color 0.2s;
}

.routine-item:hover {
  background: var(--list-item-bg-good-hover, var(--list-item-bg-good));
  border-color: var(--list-item-border-good-hover, var(--list-item-border-good));
}

.routine-item input[type='checkbox'] {
  cursor: pointer;
  width: 1.2em;
  height: 1.2em;
  margin-left: 1rem;
  accent-color: var(--checkbox-accent);
  flex-shrink: 0;
}

.routine-item img {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 6px;
  object-fit: cover;
}

.routine-item .name {
  flex: 1;
  text-align: left;
  font-weight: 600;
}

.routine-item .value {
  min-width: 60px;
  text-align: right;
  font-weight: 600;
}

.actions {
  display: flex;
  gap: 3rem;
  justify-content: center;
  margin-top: 0.5rem;
}

.actions button {
  padding: 1rem 2.2rem;
  border-radius: 12px;
  border: 0;
  cursor: pointer;
  font-weight: 700;
  font-size: 1.25rem;
  transition: background 0.18s;
  min-width: 120px;
}
</style>
