<script setup lang="ts">
import { ClassroomComplianceAPIClient, type Class } from '@/api/classroom_compliance'
import { useAuthStore } from '@/stores/auth'
import { onMounted, ref, type Ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const authStore = useAuthStore()
const route = useRoute()
const router = useRouter()
const cls: Ref<Class | null> = ref(null)

interface ClassFormData {
  number: number
  schoolYear: string
}
const formData: Ref<ClassFormData> = ref({ number: 1, schoolYear: '2024-2025' })
const apiClient = new ClassroomComplianceAPIClient(authStore)

onMounted(async () => {
  if ('classId' in route.query && typeof route.query.classId === 'string') {
    const classId = parseInt(route.query.classId, 10)
    cls.value = await apiClient.getClass(classId).handleErrorsWithAlert()
    if (!cls.value) {
      await router.back()
      return
    }
    formData.value.number = cls.value.number
    formData.value.schoolYear = cls.value.schoolYear
  }
})

async function submitForm() {
  if (cls.value) {
    // TODO: Update class
  } else {
    const result = await apiClient
      .createClass(formData.value.number, formData.value.schoolYear)
      .handleErrorsWithAlert()
    if (result) {
      await router.replace(`/classroom-compliance/classes/${result.id}`)
    }
  }
}

function resetForm() {
  if (cls.value) {
    formData.value.number = cls.value.number
    formData.value.schoolYear = cls.value.schoolYear
  } else {
    formData.value.number = 1
    formData.value.schoolYear = '2024-2025'
  }
  router.back()
}
</script>
<template>
  <div class="centered-content">
    <h2 class="align-center">
      <span v-if="cls" v-text="'Edit Class ' + cls.id"></span>
      <span v-if="!cls">Add New Class</span>
    </h2>

    <form @submit.prevent="submitForm" @reset.prevent="resetForm">
      <p>
        Add a new class to your classroom compliance app.
      </p>
      <div>
        <label for="number-input">Number</label>
        <input id="number-input" type="number" v-model="formData.number" required />
      </div>
      <div>
        <label for="school-year-input">School Year (example: "2024-2025")</label>
        <input id="school-year-input" type="text" v-model="formData.schoolYear" required />
      </div>
      <div class="button-bar">
        <button type="submit">Save</button>
        <button type="reset">Cancel</button>
      </div>
    </form>
  </div>
</template>
