<template>
  <div class="p-6 max-w-2xl mx-auto">
    <h2 class="text-2xl font-bold mb-6">✏️ Edit Student</h2>

    <form @submit.prevent="submitForm" class="space-y-4" v-if="form">
      <div>
        <label class="block font-medium">Name</label>
        <input v-model="form.name" type="text" required class="input" />
      </div>

      <div>
        <label class="block font-medium">Email</label>
        <input v-model="form.email" type="email" required class="input" />
      </div>

      <div>
        <label class="block font-medium">Phone</label>
        <input v-model="form.phone" type="text" required class="input" />
      </div>

      <div>
        <label class="block font-medium">Date of Birth</label>
        <input v-model="form.dob" type="date" required class="input" />
      </div>

      <div>
        <label class="block font-medium">Gender</label>
        <select v-model="form.gender" required class="input">
          <option value="">Select Gender</option>
          <option value="male">Male</option>
          <option value="female">Female</option>
        </select>
      </div>

      <div>
        <label class="block font-medium">Class</label>
        <select v-model="form.class_id" required class="input">
          <option value="">Select Class</option>
          <option v-for="cls in classes" :key="cls.id" :value="cls.id">
            {{ cls.name }} - {{ cls.section }}
          </option>
        </select>
      </div>

      <button type="submit" class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700">
        Update Student
      </button>
    </form>

    <div v-else class="text-gray-500">Loading student info...</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDirectus } from '../../app/composables/useDirectus'

const { fetchCollection, updateItem } = useDirectus()
const route = useRoute()
const router = useRouter()

const studentId = route.query.id
const form = ref(null)
const classes = ref([])

const fetchClasses = async () => {
  try {
    classes.value = await fetchCollection('classes', {
      fields: ['id', 'name', 'section'],
      sort: ['name']
    })
  } catch (err) {
    console.error('Error loading classes:', err)
  }
}

const fetchStudent = async () => {
  try {
    const studentData = await fetchCollection('students', {
      filter: { id: { _eq: studentId } },
      limit: 1
    })
    form.value = studentData[0] // Get first item from array
  } catch (err) {
    console.error('Error loading student:', err)
  }
}

onMounted(async () => {
  await fetchClasses()
  await fetchStudent()
})

const submitForm = async () => {
  try {
    await updateItem('students', studentId, form.value)
    alert('Student updated successfully!')
    router.push('/students')
  } catch (err) {
    console.error('Error updating student:', err)
    alert('Failed to update student.')
  }
}
</script>

<style scoped>
.input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 0.375rem;
}
</style>