<script setup lang="ts">
import { useAuthStore } from '@/stores/auth'
import { onMounted, ref, useTemplateRef, type Ref } from 'vue'
import EntriesTable from '@/apps/classroom_compliance/EntriesTable.vue'
import { useRouter } from 'vue-router'
import ConfirmDialog from '@/components/ConfirmDialog.vue'
import { ClassroomComplianceAPIClient, type Class, type ClassNote } from '@/api/classroom_compliance'
import ClassNoteItem from './ClassNoteItem.vue'

const props = defineProps<{
  id: string
}>()
const authStore = useAuthStore()
const router = useRouter()
const cls: Ref<Class | null> = ref(null)
const notes: Ref<ClassNote[]> = ref([])
const noteContent: Ref<string> = ref('')

const entriesTable = useTemplateRef('entries-table')

const apiClient = new ClassroomComplianceAPIClient(authStore)

const deleteClassDialog = useTemplateRef('deleteClassDialog')
onMounted(() => {
  loadClass()
})

function loadClass() {
  const idNumber = parseInt(props.id, 10)
  apiClient.getClass(idNumber).handleErrorsWithAlert().then(result => {
    if (result) {
      cls.value = result
      refreshNotes()
    } else {
      router.back();
    }
  })
}

async function deleteThisClass() {
  if (!cls.value || !(await deleteClassDialog.value?.show())) return
  await apiClient.deleteClass(cls.value.id).handleErrorsWithAlert()
  await router.replace('/classroom-compliance')
}

async function submitNote() {
  if (noteContent.value.trim().length < 1 || !cls.value) return
  const note = await apiClient.createClassNote(cls.value?.id, noteContent.value).handleErrorsWithAlert()
  if (note) {
    noteContent.value = ''
    const updatedNotes = await apiClient.getClassNotes(cls.value?.id).handleErrorsWithAlert()
    if (updatedNotes !== null) {
      notes.value = updatedNotes
    }
  }
}

function refreshNotes() {
  if (cls.value === null) {
    notes.value = []
    return
  }
  apiClient.getClassNotes(cls.value.id).handleErrorsWithAlert().then(notesResult => {
    if (notesResult !== null) {
      notes.value = notesResult
    } else {
      notes.value = []
    }
  })
}

async function resetStudentDesks() {
  if (!cls.value) return
  await apiClient.resetStudentDesks(cls.value.id).handleErrorsWithAlert()
  // Reload the table!
  await entriesTable.value?.loadEntries()
}
</script>
<template>
  <div v-if="cls">
    <h1 class="align-center" style="margin-bottom: 0;">Class <span v-text="cls.number"></span></h1>
    <p class="align-center" style="margin-top: 0; margin-bottom: 2em;">For the {{ cls.schoolYear }} school year.</p>
    <div class="button-bar align-center" style="margin-bottom: 1em;">
      <button type="button" @click="router.push(`/classroom-compliance/classes/${cls.id}/edit-student`)">Add
        Student</button>
      <button type="button" @click="router.push(`/classroom-compliance/classes/${cls.id}/import-students`)">Import
        Students</button>
      <button type="button" @click="resetStudentDesks">Clear Assigned Desks</button>
      <button type="button" @click="deleteThisClass">Delete this Class</button>
    </div>

    <EntriesTable :classId="cls.id" ref="entries-table" />

    <div>
      <h3 style="margin-bottom: 0.25em;">Notes</h3>
      <form @submit.prevent="submitNote">
        <textarea style="min-height: 50px; min-width: 300px;" maxlength="2000" minlength="1"
          v-model="noteContent"></textarea>
        <button style="vertical-align: top; margin-left: 0.5em;" type="submit">Add Note</button>
      </form>
      <ClassNoteItem v-for="note in notes" :key="note.id" :note="note" @noteDeleted="refreshNotes()" />
    </div>

    <!-- Confirmation dialog used for attempts at deleting this class. -->
    <ConfirmDialog ref="deleteClassDialog">
      <p>
        Are you sure you want to delete this class? All data associated with it (settings, students,
        entries, grades, etc.) will be <strong>permanently deleted</strong>, and deleted data is not
        recoverable.
      </p>
    </ConfirmDialog>
  </div>
</template>
