<script setup>
import { onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { getStudents, createStudent, updateStudent, deleteStudent } from '@/api/studentService.js'
import { useCrudList } from '@/composables/useCrudList.js'
import { useFlashMessage } from '@/composables/useFlashMessage.js'
import StudentTable from '@/components/student/StudentTable.vue'
import StudentEditDialog from '@/components/student/StudentEditDialog.vue'
import StudentDeleteDialog from '@/components/student/StudentDeleteDialog.vue'

const { t } = useI18n()

const crud = useCrudList({
  list: getStudents,
  create: createStudent,
  update: updateStudent,
  deleteFn: deleteStudent,
  idKey: 'student_id',
  loadErrorKey: t('student.messages.loadError'),
})

const flash = useFlashMessage()

onMounted(() => {
  crud.fetch()
})

function onSaved(entity) {
  const isCreate = crud.applySaved(entity)
  flash.show(t(isCreate ? 'student.messages.createSuccess' : 'student.messages.updateSuccess'))
}

function onDeleted(id) {
  const item = crud.items.value.find((s) => s.student_id === id)
  crud.applyDeleted(id)
  flash.show(t('student.messages.deleteSuccess', { name: item?.student_name ?? '' }))
  crud.closeEdit()
}
</script>

<template>
  <v-container fluid>
    <v-row class="mb-4" align="center" justify="space-between">
      <v-col cols="12" sm="6">
        <h2 class="text-h5">{{ t('student.title') }}</h2>
      </v-col>
      <v-col cols="12" sm="6" class="text-sm-right text-right">
        <v-btn
          color="success"
          prepend-icon="mdi-plus"
          class="mr-2"
          @click="crud.openCreate()"
        >
          {{ t('student.buttons.addStudent') }}
        </v-btn>
        <v-btn
          color="primary"
          prepend-icon="mdi-refresh"
          :loading="crud.isLoading.value"
          @click="crud.fetch()"
        >
          {{ t('common.buttons.refresh') }}
        </v-btn>
      </v-col>
    </v-row>

    <v-alert
      v-if="flash.message.value"
      type="success"
      class="mb-4"
      closable
      @click:close="flash.clear()"
    >
      {{ flash.message.value }}
    </v-alert>

    <v-alert v-if="crud.isError.value" type="error" class="mb-4" closable>
      {{ crud.errorMessage.value }}
    </v-alert>

    <v-progress-linear
      v-if="crud.isLoading.value"
      indeterminate
      color="primary"
      class="mb-4"
    ></v-progress-linear>

    <StudentTable
      :items="crud.items.value"
      @edit="crud.openEdit"
      @delete="crud.openDelete"
    />

    <StudentEditDialog
      :open="crud.editingDialogOpen.value"
      :student="crud.editingItem.value"
      @close="crud.closeEdit()"
      @saved="onSaved"
    />

    <StudentDeleteDialog
      :open="crud.deleteDialogOpen.value"
      :student="crud.itemToDelete.value"
      @close="crud.closeDelete()"
      @deleted="onDeleted"
    />
  </v-container>
</template>