<script setup>
import { onMounted, ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useDisplay } from 'vuetify'
import { getStories, updateStory, createStory, deleteStory } from '@/api/storyService.js'
import { getStudents } from '@/api/studentService.js'
import { getSubjects } from '@/api/subjectService.js'
import { getTerms } from '@/api/termService.js'
import { fromApiBool } from '@/api/boolCodec.js'

const { xs } = useDisplay()

const { t } = useI18n()

const isLoading = ref(false)
const isError = ref(false)
const errorMessage = ref('')
const stories = ref([])

// 关联数据
const students = ref([])
const subjects = ref([])
const terms = ref([])
const isLoadingRelatedData = ref(false)

// 编辑功能相关状态
const editDialog = ref(false)
const editingStory = ref(null)
const editForm = ref({
  story_name: '',
  description: '',
  student_id: null,
  subject_id: null,
  term_id: null,
  tracked_flag: 'N',
})
const isSaving = ref(false)
const successMessage = ref('')
const saveErrorMessage = ref('')

// 新增功能相关状态
const createDialog = ref(false)
const createForm = ref({
  story_name: '',
  description: '',
  student_id: null,
  subject_id: null,
  term_id: null,
  tracked_flag: 'N',
})
const isCreating = ref(false)
const createErrorMessage = ref('')

// 删除功能相关状态
const deleteDialog = ref(false)
const storyToDelete = ref(null)
const isDeleting = ref(false)

const headers = computed(() => [
  { title: t('story.tableHeader.storyName'), value: 'story_name', sortable: true, width: '20%' },
  {
    title: t('story.tableHeader.description'),
    value: 'description',
    sortable: false,
    width: '20%',
  },
  { title: t('story.tableHeader.studentId'), value: 'student_id', sortable: true, width: '15%' },
  { title: t('story.tableHeader.subjectId'), value: 'subject_id', sortable: true, width: '15%' },
  { title: t('story.tableHeader.termId'), value: 'term_id', sortable: true, width: '15%' },
  {
    title: t('story.tableHeader.trackedFlag'),
    value: 'tracked_flag',
    sortable: true,
    width: '15%',
    sort: (a, b) => {
      if (fromApiBool(a) && !fromApiBool(b)) return -1
      if (!fromApiBool(a) && fromApiBool(b)) return 1
      return 0
    },
  },
  {
    title: t('story.tableHeader.actions'),
    value: 'actions',
    sortable: false,
    align: 'end',
    width: '12%',
  },
])

// 获取系列任务数据
const fetchStories = async () => {
  isLoading.value = true
  isError.value = false
  errorMessage.value = ''
  try {
    const storiesData = await getStories()
    console.log('Stories data:', storiesData)
    stories.value = Array.isArray(storiesData) ? storiesData : []

    // 为每个story添加关联数据的名称
    stories.value.forEach((story) => {
      story.student_name = getStudentName(story.student_id)
      story.subject_name = getSubjectName(story.subject_id)
      story.term_name = getTermName(story.term_id)
    })
  } catch (e) {
    isError.value = true
    errorMessage.value = e?.response?.data?.detail || e?.message || t('story.message.loadError')
    // 3秒后自动隐藏错误消息
    setTimeout(() => {
      isError.value = false
      errorMessage.value = ''
    }, 3000)
  } finally {
    isLoading.value = false
  }
}

// 获取关联数据（学生、学科、学期）
const fetchRelatedData = async () => {
  isLoadingRelatedData.value = true
  try {
    const [studentsData, subjectsData, termsData] = await Promise.all([
      getStudents(),
      getSubjects(),
      getTerms(),
    ])

    students.value = studentsData
    subjects.value = subjectsData
    terms.value = termsData

    console.log('Related data loaded:', {
      students: students.value.length,
      subjects: subjects.value.length,
      terms: terms.value.length,
    })
  } catch (error) {
    console.error('Failed to load related data:', error)
  } finally {
    isLoadingRelatedData.value = false
  }
}

onMounted(() => {
  fetchStories()
  fetchRelatedData()
})

// 编辑功能方法
const openEditDialog = (story) => {
  editingStory.value = story
  editForm.value = {
    story_name: story.story_name || '',
    description: story.description || '',
    student_id: story.student_id || null,
    subject_id: story.subject_id || null,
    term_id: story.term_id || null,
    tracked_flag: story.tracked_flag || 'N',
  }
  console.log('Editing story data:', story)
  console.log('Converted form data:', editForm.value)
  editDialog.value = true
}

const closeEditDialog = () => {
  editDialog.value = false
  editingStory.value = null
  editForm.value = {
    story_name: '',
    description: '',
    student_id: null,
    subject_id: null,
    term_id: null,
    tracked_flag: 'N',
  }
}

const saveStory = async () => {
  // 检查是否有正在编辑的故事以及故事ID
  if (!editingStory.value?.story_id) {
    saveErrorMessage.value = t('common.messages.error.general')
    // 3秒后自动隐藏错误消息
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
    return
  }

  isSaving.value = true
  saveErrorMessage.value = ''
  successMessage.value = ''

  try {
    console.log('Form data before update:', editForm.value)

    // 构建要发送的数据
    const updateData = {
      story_name: editForm.value.story_name,
      description: editForm.value.description,
      student_id: editForm.value.student_id,
      subject_id: editForm.value.subject_id,
      term_id: editForm.value.term_id,
      tracked_flag: editForm.value.tracked_flag,
    }

    console.log('Sending data:', updateData)

    // 1. 调用API更新系列任务
    await updateStory(editingStory.value.story_id, updateData)

    // 2. 更新本地数据
    const index = stories.value.findIndex((s) => s.story_id === editingStory.value.story_id)
    if (index !== -1) {
      stories.value[index] = {
        ...stories.value[index],
        ...updateData,
      }
    }

    // 3. 显示成功消息
    successMessage.value = t('story.message.updateSuccess')
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
    closeEditDialog()
  } catch (error) {
    console.error('Update failed:', error)
    saveErrorMessage.value = error.message || t('story.message.updateError')
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
  } finally {
    isSaving.value = false
  }
}

// 新增功能方法
const openCreateDialog = () => {
  createForm.value = {
    story_name: '',
    description: '',
    student_id: null,
    subject_id: null,
    term_id: null,
    tracked_flag: 'N',
  }
  createErrorMessage.value = ''
  createDialog.value = true
}

const closeCreateDialog = () => {
  createDialog.value = false
  createForm.value = {
    story_name: '',
    description: '',
    student_id: null,
    subject_id: null,
    term_id: null,
    tracked_flag: 'N',
  }
  createErrorMessage.value = ''
}

const createNewStory = async () => {
  isCreating.value = true
  createErrorMessage.value = ''
  successMessage.value = ''

  try {
    console.log('Form data before creation:', createForm.value)

    // 构建要发送的数据
    const createData = {
      story_name: createForm.value.story_name,
      description: createForm.value.description,
      student_id: createForm.value.student_id,
      subject_id: createForm.value.subject_id,
      term_id: createForm.value.term_id,
      tracked_flag: createForm.value.tracked_flag,
    }

    console.log('Sending data:', createData)

    // 1. 调用API创建系列任务
    const newStory = await createStory(createData)

    // 2. 创建成功后，将新系列任务添加到本地列表
    const storyToAdd = {
      ...newStory,
      ...createData,
    }

    stories.value.unshift(storyToAdd) // 在列表顶部添加新系列任务

    // 3. 显示成功消息
    successMessage.value = t('story.message.createSuccess')
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
    closeCreateDialog()
  } catch (error) {
    console.error('Creation failed:', error)
    createErrorMessage.value = error.message || t('story.message.createError')
    setTimeout(() => {
      createErrorMessage.value = ''
    }, 3000)
  } finally {
    isCreating.value = false
  }
}

// 删除功能方法
const openDeleteDialog = (story) => {
  storyToDelete.value = story
  deleteDialog.value = true
}

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

const confirmDelete = async () => {
  if (!storyToDelete.value?.story_id) {
    console.error('Unable to get story ID')
    return
  }

  isDeleting.value = true

  try {
    console.log('Deleting story:', storyToDelete.value)

    // 1. 调用API删除系列任务
    await deleteStory(storyToDelete.value.story_id)

    // 2. 从本地列表中移除
    const index = stories.value.findIndex((s) => s.story_id === storyToDelete.value.story_id)
    if (index !== -1) {
      stories.value.splice(index, 1)
    }

    // 3. 显示成功消息
    successMessage.value = t('story.message.deleteSuccess')
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)

    closeDeleteDialog()
    closeEditDialog() // 自动关闭编辑对话框
  } catch (error) {
    console.error('Deletion failed:', error)
    // 在删除对话框中显示错误，但不关闭对话框
    saveErrorMessage.value = error.message || t('story.message.deleteError')
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
  } finally {
    isDeleting.value = false
  }
}

// 格式化显示
const getStudentName = (studentId) => {
  const student = students.value.find((s) => s.student_id === studentId)
  return student ? student.student_name : studentId
}

const getSubjectName = (subjectId) => {
  const subject = subjects.value.find((s) => s.subject_id === subjectId)
  return subject ? subject.subject_name : subjectId
}

const getTermName = (termId) => {
  const term = terms.value.find((t) => t.term_id === termId)
  return term ? term.term_name : termId
}

const getTrackedStatus = (flag) => {
  return fromApiBool(flag) ? t('story.status.tracked') : t('story.status.notTracked')
}
</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="openCreateDialog">
          {{ 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="successMessage"
      type="success"
      class="mb-4"
      closable
      @click:close="successMessage = ''"
    >
      {{ successMessage }}
    </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>

    <!-- 数据表格 -->
    <v-data-table
      :headers="headers"
      :items="stories"
      item-key="story_id"
      :items-per-page="10"
      class="elevation-1 text-no-wrap"
      :sort-by="[{ key: 'story_name', order: 'asc' }]"
      multi-sort
      :items-per-page-text="t('common.table.pagination.itemsPerPage')"
      :no-data-text="t('common.table.pagination.noDataText')"
      :loading-text="t('common.table.pagination.loadingText')"
      :items-per-page-options="[
        { value: 5, title: '5' },
        { value: 10, title: '10' },
        { value: 25, title: '25' },
        { value: 50, title: '50' },
        { value: -1, title: t('common.table.pagination.itemsPerPageAll') },
      ]"
      :hide-default-footer="false"
      :height="xs ? undefined : 'calc(100dvh - 360px)'"
      :fixed-header="!xs"
      :density="xs ? 'compact' : 'comfortable'"
    >
      <template v-slot:[`item.student_id`]="{ item }">
        {{ getStudentName(item.student_id) }}
      </template>

      <template v-slot:[`item.subject_id`]="{ item }">
        {{ getSubjectName(item.subject_id) }}
      </template>

      <template v-slot:[`item.term_id`]="{ item }">
        {{ getTermName(item.term_id) }}
      </template>

      <template v-slot:[`item.tracked_flag`]="{ item }">
        <v-chip
          :color="fromApiBool(item.tracked_flag) ? 'success' : 'grey'"
          text-color="white"
          size="small"
        >
          {{ getTrackedStatus(item.tracked_flag) }}
        </v-chip>
      </template>

      <template v-slot:[`item.actions`]="{ item }">
        <v-btn
          icon="mdi-pencil"
          size="small"
          color="primary"
          variant="text"
          @click="openEditDialog(item)"
        >
        </v-btn>
      </template>
    </v-data-table>
  </v-container>

  <!-- 编辑对话框 -->
  <v-dialog v-model="editDialog" max-width="600px">
    <v-card>
      <v-card-title>{{ t('story.dialog.edit') }}</v-card-title>
      <v-card-text>
        <v-alert v-if="saveErrorMessage" type="error" variant="tonal" closable class="mb-4">
          {{ saveErrorMessage }}
        </v-alert>

        <v-form @submit.prevent="saveStory">
          <v-container>
            <v-row>
              <v-col cols="12">
                <v-text-field
                  v-model="editForm.story_name"
                  :label="t('story.form.storyName') + ' *'"
                  required
                  :rules="[(v) => !!v || t('story.validation.storyNameRequired')]"
                  variant="outlined"
                ></v-text-field>
              </v-col>

              <v-col cols="12">
                <v-textarea
                  v-model="editForm.description"
                  :label="t('story.form.description')"
                  rows="3"
                  variant="outlined"
                ></v-textarea>
              </v-col>

              <v-col cols="12" md="6">
                <v-select
                  v-model="editForm.student_id"
                  :items="students"
                  item-title="student_name"
                  item-value="student_id"
                  :label="t('story.form.studentId') + ' *'"
                  required
                  :rules="[(v) => !!v || t('story.validation.studentRequired')]"
                  :loading="isLoadingRelatedData"
                  variant="outlined"
                ></v-select>
              </v-col>

              <v-col cols="12" md="6">
                <v-select
                  v-model="editForm.subject_id"
                  :items="subjects"
                  item-title="subject_name"
                  item-value="subject_id"
                  :label="t('story.form.subjectId') + ' *'"
                  required
                  :rules="[(v) => !!v || t('story.validation.subjectRequired')]"
                  :loading="isLoadingRelatedData"
                  variant="outlined"
                ></v-select>
              </v-col>

              <v-col cols="12" md="6">
                <v-select
                  v-model="editForm.term_id"
                  :items="terms"
                  item-title="term_name"
                  item-value="term_id"
                  :label="t('story.form.termId') + ' *'"
                  required
                  :rules="[(v) => !!v || t('story.validation.termRequired')]"
                  :loading="isLoadingRelatedData"
                  variant="outlined"
                ></v-select>
              </v-col>

              <v-col cols="12" md="6">
                <v-switch
                  v-model="editForm.tracked_flag"
                  :label="t('story.form.trackedFlag')"
                  color="primary"
                  true-value="Y"
                  false-value="N"
                  inset
                ></v-switch>
              </v-col>
            </v-row>
          </v-container>
        </v-form>
      </v-card-text>
      <v-card-actions>
        <v-btn
          color="error"
          variant="outlined"
          prepend-icon="mdi-delete"
          @click="openDeleteDialog(editingStory)"
          :disabled="isSaving"
        >
          {{ t('common.buttons.delete') }}
        </v-btn>
        <v-spacer></v-spacer>
        <v-btn color="grey-darken-1" variant="text" @click="closeEditDialog">
          {{ t('common.buttons.cancel') }}
        </v-btn>
        <v-btn
          color="primary"
          variant="text"
          @click="saveStory"
          :loading="isSaving"
          :disabled="isSaving"
        >
          {{ t('common.buttons.save') }}
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>

  <!-- 新增对话框 -->
  <v-dialog v-model="createDialog" max-width="600px">
    <v-card>
      <v-card-title>{{ t('story.dialog.create') }}</v-card-title>
      <v-card-text>
        <v-alert v-if="createErrorMessage" type="error" variant="tonal" closable class="mb-4">
          {{ createErrorMessage }}
        </v-alert>

        <v-form @submit.prevent="createNewStory">
          <v-container>
            <v-row>
              <v-col cols="12">
                <v-text-field
                  v-model="createForm.story_name"
                  :label="t('story.form.storyName') + ' *'"
                  required
                  :rules="[(v) => !!v || t('story.validation.storyNameRequired')]"
                  variant="outlined"
                ></v-text-field>
              </v-col>

              <v-col cols="12">
                <v-textarea
                  v-model="createForm.description"
                  :label="t('story.form.description')"
                  rows="3"
                  variant="outlined"
                ></v-textarea>
              </v-col>

              <v-col cols="12" md="6">
                <v-select
                  v-model="createForm.student_id"
                  :items="students"
                  item-title="student_name"
                  item-value="student_id"
                  :label="t('story.form.studentId') + ' *'"
                  required
                  :rules="[(v) => !!v || t('story.validation.studentRequired')]"
                  :loading="isLoadingRelatedData"
                  variant="outlined"
                ></v-select>
              </v-col>

              <v-col cols="12" md="6">
                <v-select
                  v-model="createForm.subject_id"
                  :items="subjects"
                  item-title="subject_name"
                  item-value="subject_id"
                  :label="t('story.form.subjectId') + ' *'"
                  required
                  :rules="[(v) => !!v || t('story.validation.subjectRequired')]"
                  :loading="isLoadingRelatedData"
                  variant="outlined"
                ></v-select>
              </v-col>

              <v-col cols="12" md="6">
                <v-select
                  v-model="createForm.term_id"
                  :items="terms"
                  item-title="term_name"
                  item-value="term_id"
                  :label="t('story.form.termId') + ' *'"
                  required
                  :rules="[(v) => !!v || t('story.validation.termRequired')]"
                  :loading="isLoadingRelatedData"
                  variant="outlined"
                ></v-select>
              </v-col>

              <v-col cols="12" md="6">
                <v-switch
                  v-model="createForm.tracked_flag"
                  :label="t('story.form.trackedFlag')"
                  color="primary"
                  true-value="Y"
                  false-value="N"
                  inset
                ></v-switch>
              </v-col>
            </v-row>
          </v-container>
        </v-form>
      </v-card-text>
      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn color="grey-darken-1" variant="text" @click="closeCreateDialog">
          {{ t('common.buttons.cancel') }}
        </v-btn>
        <v-btn
          color="success"
          variant="text"
          @click="createNewStory"
          :loading="isCreating"
          :disabled="isCreating"
        >
          {{ t('common.buttons.create') }}
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>

  <!-- 删除确认对话框 -->
  <v-dialog v-model="deleteDialog" max-width="400px">
    <v-card>
      <v-card-title class="text-h5 text-error">
        <v-icon icon="mdi-alert" class="mr-2" />
        {{ t('story.deleteConfirm.title') }}
      </v-card-title>
      <v-card-text>
        <div class="text-body-1 mb-4">
          {{ t('story.deleteConfirm.message') }}
        </div>
        <div v-if="storyToDelete" class="bg-grey-lighten-4 pa-3 rounded">
          <div class="font-weight-medium">{{ storyToDelete.story_name }}</div>
          <div class="text-caption text-medium-emphasis">
            {{
              t('story.deleteConfirm.storyInfo', {
                name: storyToDelete.story_name,
              })
            }}
          </div>
        </div>
        <div class="text-body-2 text-error mt-4">
          <v-icon icon="mdi-alert-circle" size="small" class="mr-1" />
          {{ t('story.deleteConfirm.warning') }}
        </div>
      </v-card-text>
      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn
          color="grey-darken-1"
          variant="text"
          @click="closeDeleteDialog"
          :disabled="isDeleting"
        >
          {{ t('common.buttons.cancel') }}
        </v-btn>
        <v-btn
          color="error"
          variant="elevated"
          prepend-icon="mdi-delete"
          @click="confirmDelete"
          :loading="isDeleting"
          :disabled="isDeleting"
        >
          {{ t('common.buttons.confirm') + ' ' + t('common.buttons.delete') }}
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<style scoped>
.v-data-table {
  width: 100%;
}
</style>
