<script setup>
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import {
  getStories,
  createStory,
  updateStory,
  deleteStory,
} from '@/api/storyService.js'
import { getStudents } from '@/api/studentService.js'
import { getSubjects } from '@/api/subjectService.js'
import { getTerms } from '@/api/termService.js'
import { useCrudList } from '@/composables/useCrudList.js'
import { useFlashMessage } from '@/composables/useFlashMessage.js'
import StoryTable from '@/components/story/StoryTable.vue'
import StoryEditDialog from '@/components/story/StoryEditDialog.vue'
import StoryDeleteDialog from '@/components/story/StoryDeleteDialog.vue'

const { t } = useI18n()

// View-owned reference data (per R2 — composable does not see it).
const students = ref([])
const subjects = ref([])
const terms = ref([])

const crud = useCrudList({
  list: getStories,
  create: createStory,
  update: updateStory,
  deleteFn: deleteStory,
  idKey: 'story_id',
  loadErrorKey: t('story.message.loadError'),
})

const flash = useFlashMessage()

async function fetchRelatedData() {
  try {
    const [studentsData, subjectsData, termsData] = await Promise.all([
      getStudents(),
      getSubjects(),
      getTerms(),
    ])
    students.value = studentsData
    subjects.value = subjectsData
    terms.value = termsData
  } catch (error) {
    console.error('Failed to load related data:', error)
  }
}

// fetchStories must run AFTER fetchRelatedData — the table relies on
// student/subject/term arrays being populated for its Map computeds.
// Do NOT switch to Promise.all (see Candidate 2's TaskView for contrast).
onMounted(async () => {
  await fetchRelatedData()
  await crud.fetch()
})

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

function onDeleted(id) {
  const item = crud.items.value.find((s) => s.story_id === id)
  crud.applyDeleted(id)
  flash.show(t('story.message.deleteSuccess', { name: item?.story_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('story.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('story.button.create') }}
        </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>

    <StoryTable
      :stories="crud.items.value"
      :students="students"
      :subjects="subjects"
      :terms="terms"
      @edit="crud.openEdit"
      @delete="crud.openDelete"
    />

    <StoryEditDialog
      :open="crud.editingDialogOpen.value"
      :story="crud.editingItem.value"
      :students="students"
      :subjects="subjects"
      :terms="terms"
      @close="crud.closeEdit()"
      @saved="onSaved"
    />

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