<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)"
        >
          <input
            type="checkbox"
            :checked="selectedIds.includes(routine.id)"
            @change="toggleRoutine(routine.id)"
            :aria-label="`Select ${routine.name}`"
          />
          <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>
        </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>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import MessageBlock from '../shared/MessageBlock.vue'
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
    const routinesResp = await fetch('/api/routine/list')
    if (!routinesResp.ok) throw new Error('Failed to fetch routines')
    const routinesData = await routinesResp.json()
    routines.value = routinesData.routines || []
  } 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 fetch(`/api/child/${childId}/set-routines`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ routine_ids: 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: 1rem;
  gap: 1rem;
}

h2 {
  margin: 0;
  color: var(--text-primary);
  font-size: 1.5rem;
}

.list-container {
  flex: 1 1 auto;
  width: 100%;
  max-width: 500px;
  overflow-y: auto;
}

.routine-selection {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.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.25rem;
  height: 1.25rem;
}

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

.routine-item .name {
  flex: 1;
  font-weight: 600;
  color: var(--text-primary);
}

.routine-item .value {
  min-width: 60px;
  text-align: right;
  font-weight: 600;
  color: var(--text-secondary);
}

.actions {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  width: 100%;
  max-width: 500px;
  justify-content: flex-end;
}

.btn {
  padding: 0.5rem 1.5rem;
  border: none;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-primary {
  background: var(--btn-primary);
  color: #fff;
}

.btn-primary:hover:not(:disabled) {
  opacity: 0.9;
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-secondary {
  background: var(--btn-secondary);
  color: var(--btn-secondary-text);
}

.btn-secondary:hover {
  opacity: 0.8;
}

.round-btn {
  background: none;
  border: none;
  color: var(--btn-primary);
  font-weight: 600;
  cursor: pointer;
  text-decoration: underline;
}

.round-btn:hover {
  opacity: 0.8;
}
</style>
