<template>
  <div class="child-edit-view">
    <h2>{{ isEdit ? 'Edit Child' : 'Create Child' }}</h2>
    <div v-if="loading" class="loading-message">Loading child...</div>
    <form v-else @submit.prevent="submit" class="child-edit-form">
      <div class="group">
        <label for="child-name">Name</label>
        <input type="text" id="child-name" ref="nameInput" v-model="name" required maxlength="64" />
      </div>
      <div class="group">
        <label for="child-age">Age</label>
        <input id="child-age" v-model.number="age" type="number" min="0" max="120" required />
      </div>
      <div class="group">
        <label for="child-image">Image</label>
        <ImagePicker
          id="child-image"
          v-model="selectedImageId"
          :image-type="1"
          @add-image="onAddImage"
        />
      </div>
      <div v-if="error" class="error">{{ error }}</div>
      <div class="actions">
        <button type="button" class="btn btn-secondary" @click="onCancel" :disabled="loading">
          Cancel
        </button>
        <button type="submit" class="btn btn-primary" :disabled="loading">
          {{ isEdit ? 'Save' : 'Create' }}
        </button>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ImagePicker from '@/components/utils/ImagePicker.vue'
import '@/assets/edit-forms.css'

const route = useRoute()
const router = useRouter()

// Accept id as a prop for edit mode
const props = defineProps<{ id?: string }>()

const isEdit = computed(() => !!props.id)
const name = ref('')
const age = ref<number | null>(null)
const selectedImageId = ref<string | null>(null)
const localImageFile = ref<File | null>(null)
const nameInput = ref<HTMLInputElement | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)

onMounted(async () => {
  if (isEdit.value && props.id) {
    loading.value = true
    try {
      const resp = await fetch(`/api/child/${props.id}`)
      if (!resp.ok) throw new Error('Failed to load child')
      const data = await resp.json()
      name.value = data.name ?? ''
      age.value = Number(data.age) ?? null
      selectedImageId.value = data.image_id ?? null
    } catch (e) {
      error.value = 'Could not load child.'
    } finally {
      loading.value = false
      await nextTick()
      nameInput.value?.focus()
    }
  } else {
    await nextTick()
    nameInput.value?.focus()
  }
})

function onAddImage({ id, file }: { id: string; file: File }) {
  if (id === 'local-upload') {
    localImageFile.value = file
  }
}

const submit = async () => {
  let imageId = selectedImageId.value
  error.value = null
  if (!name.value.trim()) {
    error.value = 'Child name is required.'
    return
  }
  if (age.value === null || age.value < 0) {
    error.value = 'Age must be a non-negative number.'
    return
  }
  loading.value = true

  // If the selected image is a local upload, upload it first
  if (imageId === 'local-upload' && localImageFile.value) {
    const formData = new FormData()
    formData.append('file', localImageFile.value)
    formData.append('type', '1')
    formData.append('permanent', 'false')
    try {
      const resp = await fetch('/api/image/upload', {
        method: 'POST',
        body: formData,
      })
      if (!resp.ok) throw new Error('Image upload failed')
      const data = await resp.json()
      imageId = data.id
    } catch (err) {
      alert('Failed to upload image.')
      loading.value = false
      return
    }
  }

  // Now update or create the child
  try {
    let resp
    if (isEdit.value && props.id) {
      resp = await fetch(`/api/child/${props.id}/edit`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name.value,
          age: age.value,
          image_id: imageId,
        }),
      })
    } else {
      resp = await fetch('/api/child/add', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name.value,
          age: age.value,
          image_id: imageId,
        }),
      })
    }
    if (!resp.ok) throw new Error('Failed to save child')
    await router.push({ name: 'ParentChildrenListView' })
  } catch (err) {
    alert('Failed to save child.')
  }
  loading.value = false
}

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

<style scoped></style>
