<template>
  <div class="reward-edit-view">
    <h2>{{ isEdit ? 'Edit Reward' : 'Create Reward' }}</h2>
    <div v-if="loading" class="loading-message">Loading reward...</div>
    <form v-else @submit.prevent="submit" class="reward-form">
      <div class="group">
        <label>
          Reward Name
          <input ref="nameInput" v-model="name" type="text" required maxlength="64" />
        </label>
      </div>
      <div class="group">
        <label>
          Description
          <input v-model="description" type="text" maxlength="128" />
        </label>
      </div>
      <div class="group">
        <label>
          Cost
          <input v-model.number="cost" type="number" min="1" max="1000" required />
        </label>
      </div>
      <div class="group">
        <label for="reward-image">Image</label>
        <ImagePicker
          id="reward-image"
          v-model="selectedImageId"
          :image-type="2"
          @add-image="onAddImage"
        />
      </div>
      <div v-if="error" class="error">{{ error }}</div>
      <div class="actions">
        <button type="button" @click="handleCancel" :disabled="loading" class="btn btn-secondary">
          Cancel
        </button>
        <button type="submit" :disabled="loading" class="btn btn-primary">
          {{ 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 props = defineProps<{ id?: string }>()
const route = useRoute()
const router = useRouter()
const isEdit = computed(() => !!props.id)

const name = ref('')
const description = ref('')
const cost = ref(1)
const selectedImageId = ref<string | null>(null)
const localImageFile = ref<File | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const nameInput = ref<HTMLInputElement | null>(null)

onMounted(async () => {
  if (isEdit.value && props.id) {
    loading.value = true
    try {
      const resp = await fetch(`/api/reward/${props.id}`)
      if (!resp.ok) throw new Error('Failed to load reward')
      const data = await resp.json()
      name.value = data.name
      description.value = data.description ?? ''
      cost.value = Number(data.cost) || 1
      selectedImageId.value = data.image_id ?? null
    } catch (e) {
      error.value = 'Could not load reward.'
    } 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
  }
}

function handleCancel() {
  router.back()
}

const submit = async () => {
  let imageId = selectedImageId.value
  error.value = null
  if (!name.value.trim()) {
    error.value = 'Reward name is required.'
    return
  }
  if (cost.value < 1) {
    error.value = 'Cost must be at least 1.'
    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', '2')
    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 reward
  try {
    let resp
    if (isEdit.value && props.id) {
      resp = await fetch(`/api/reward/${props.id}/edit`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name.value,
          description: description.value,
          cost: cost.value,
          image_id: imageId,
        }),
      })
    } else {
      resp = await fetch('/api/reward/add', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name.value,
          description: description.value,
          cost: cost.value,
          image_id: imageId,
        }),
      })
    }
    if (!resp.ok) throw new Error('Failed to save reward')
    await router.push({ name: 'RewardView' })
  } catch (err) {
    alert('Failed to save reward.')
  }
  loading.value = false
}
</script>

<style scoped></style>
