<script setup>
import { onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { getSubjects, createSubject, updateSubject, deleteSubject } from '@/api/subjectService.js'
import { COLOR_KEYS, COLOR_MAPPING } from '@/components/constants/colors'
import { useCrudList } from '@/composables/useCrudList.js'
import { useFlashMessage } from '@/composables/useFlashMessage.js'
import SubjectTable from '@/components/subject/SubjectTable.vue'
import SubjectEditDialog from '@/components/subject/SubjectEditDialog.vue'
import SubjectDeleteDialog from '@/components/subject/SubjectDeleteDialog.vue'

const { t } = useI18n()

const crud = useCrudList({
  list: getSubjects,
  create: createSubject,
  update: updateSubject,
  deleteFn: deleteSubject,
  idKey: 'subject_id',
  loadErrorKey: t('subject.messages.loadError'),
})

const flash = useFlashMessage()

// Calendar color options for the edit dialog's <v-select>. Built once with
// translated titles; passed down as a prop.
const calendarColorOptions = computed(() =>
  COLOR_KEYS.map((colorKey) => ({
    value: colorKey,
    title: t(`subject.calendarColors.${colorKey}`),
    color: COLOR_MAPPING[colorKey],
  })),
)

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

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

function onDeleted(id) {
  // capture name before splice for the success message
  const item = crud.items.value.find((s) => s.subject_id === id)
  crud.applyDeleted(id)
  flash.show(t('subject.messages.deleteSuccess', { name: item?.subject_name ?? '' }))
  // Also close edit dialog if it happened to be open against this row —
  // mirrors the previous UX contract.
  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('subject.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('subject.buttons.addSubject') }}
        </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>

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

    <SubjectEditDialog
      :open="crud.editingDialogOpen.value"
      :subject="crud.editingItem.value"
      :color-options="calendarColorOptions"
      @close="crud.closeEdit()"
      @saved="onSaved"
    />

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