<script setup>
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { getStories } from '@/api/storyService.js'
import { getStudents } from '@/api/studentService.js'
import { getSubjects } from '@/api/subjectService.js'
import { getTerms } from '@/api/termService.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()

// List + reference data
const stories = ref([])
const students = ref([])
const subjects = ref([])
const terms = ref([])

// Fetch state for stories list
const isLoading = ref(false)
const isError = ref(false)
const errorMessage = ref('')

// Dialog open state
const editDialog = ref(false)
const editingStory = ref(null) // null = create, object = edit
const deleteDialog = ref(false)
const storyToDelete = ref(null)

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)
  }
}

async function fetchStories() {
  isLoading.value = true
  isError.value = false
  errorMessage.value = ''
  try {
    const data = await getStories()
    stories.value = Array.isArray(data) ? data : []
  } catch (e) {
    isError.value = true
    errorMessage.value = e?.response?.data?.detail || e?.message || t('story.message.loadError')
    setTimeout(() => {
      isError.value = false
      errorMessage.value = ''
    }, 3000)
  } finally {
    isLoading.value = false
  }
}

// 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 fetchStories()
})

function openEditForStory(story) {
  editingStory.value = story
  editDialog.value = true
}

function openCreateForStory() {
  editingStory.value = null
  editDialog.value = true
}

function openDeleteForStory(story) {
  storyToDelete.value = story
  deleteDialog.value = true
}

function closeEditDialog() {
  editDialog.value = false
  editingStory.value = null
}

function closeDeleteDialog() {
  deleteDialog.value = false
  storyToDelete.value = null
}

function onStorySaved(updated) {
  if (!updated?.story_id) return
  const idx = stories.value.findIndex((s) => s.story_id === updated.story_id)
  const isUpdate = idx !== -1
  if (isUpdate) {
    stories.value[idx] = { ...stories.value[idx], ...updated }
  } else {
    stories.value.unshift(updated)
  }
  closeEditDialog()
  flash.show(
    isUpdate ? t('story.message.updateSuccess') : t('story.message.createSuccess'),
  )
}

function onStoryDeleted(deletedId) {
  const idx = stories.value.findIndex((s) => s.story_id === deletedId)
  if (idx !== -1) stories.value.splice(idx, 1)
  closeDeleteDialog()
  // Mirror the original "close edit dialog too" contract so the user
  // doesn't return to an edit form for a story that no longer exists.
  closeEditDialog()
  flash.show(t('story.message.deleteSuccess'))
}
</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="openCreateForStory">
          {{ t('story.button.create') }}
        </v-btn>
        <v-btn
          color="primary"
          prepend-icon="mdi-refresh"
          :loading="isLoading"
          @click="fetchStories"
        >
          {{ 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="isError" type="error" class="mb-4" closable>
      {{ errorMessage }}
    </v-alert>

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

    <StoryTable
      :stories="stories"
      :students="students"
      :subjects="subjects"
      :terms="terms"
      @edit="openEditForStory"
      @delete="openDeleteForStory"
    />

    <StoryEditDialog
      :open="editDialog"
      :story="editingStory"
      :students="students"
      :subjects="subjects"
      :terms="terms"
      @close="closeEditDialog"
      @saved="onStorySaved"
    />

    <StoryDeleteDialog
      :open="deleteDialog"
      :story="storyToDelete"
      @close="closeDeleteDialog"
      @deleted="onStoryDeleted"
    />
  </v-container>
</template>