<script setup>
import { onMounted, ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
import { getStudents, updateStudent, createStudent, deleteStudent } from '@/api/studentService.js'

const { t } = useI18n()
const authStore = useAuthStore()

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

// 编辑功能相关状态
const editDialog = ref(false)
const editingStudent = ref(null)
const editForm = ref({
  student_name: '',
  age: '',
  grade: '',
  enabled: true,
  avatar: '',
  avatar_mime_type: '',
  avatar_file_name: ''
})
const isSaving = ref(false)
const successMessage = ref('')
const saveErrorMessage = ref('')

// 新增功能相关状态
const createDialog = ref(false)
const createForm = ref({
  student_name: '',
  age: '',
  grade: '',
  enabled: true,
  avatar: '',
  avatar_mime_type: '',
  avatar_file_name: ''
})
const isCreating = ref(false)
const createErrorMessage = ref('')

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

const headers = computed(() => [
  { title: t('student.table.headers.avatar'), value: 'avatar', align: 'start', sortable: false },
  { title: t('student.table.headers.name'), value: 'student_name', sortable: true },
  {
    title: t('student.table.headers.enabled'),
    value: 'enabled',
    sortable: true,
    sort: (a, b) => {
      // Y (启用) 排在前面，N (禁用) 排在后面
      if (a === 'Y' && b === 'N') return -1
      if (a === 'N' && b === 'Y') return 1
      return 0
    }
  },
  { title: t('student.table.headers.age'), value: 'age', sortable: true },
  { title: t('student.table.headers.grade'), value: 'grade', sortable: true },
  { title: t('student.table.headers.actions'), value: 'actions', sortable: false, align: 'end' },
])

const fetchStudents = async () => {
  isLoading.value = true
  isError.value = false
  errorMessage.value = ''
  try {
    const students_data = await getStudents()
    console.log('Students data:', students_data)

    // 现在API返回的直接是数组（已经处理了所有分页）
    students.value = Array.isArray(students_data) ? students_data : []
  } catch (e) {
    isError.value = true
    errorMessage.value = e?.response?.data?.detail || e?.message || t('student.messages.loadError')
    // 3秒后自动隐藏错误消息
    setTimeout(() => {
      isError.value = false
      errorMessage.value = ''
    }, 3000)
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  // 确保 axios 鉴权拦截器与头已设置
  if (authStore && authStore.initializeAuth) {
    authStore.initializeAuth()
  }
  fetchStudents()
})

const getAvatarFallback = (name) => {
  if (!name || typeof name !== 'string') return '?'
  const t = name.trim()
  return t ? t.charAt(0).toUpperCase() : '?'
}

// 生成头像的数据URL
const getAvatarDataUrl = (avatar, mimeType) => {
  if (!avatar || !mimeType) return null
  return `data:${mimeType};base64,${avatar}`
}

// 头像上传处理
const handleAvatarUpload = (event) => {
  console.log('File upload event:', event)

  // 获取文件 - Vuetify 3 的 v-file-input 事件处理
  const files = event.target?.files || event
  const file = Array.isArray(files) ? files[0] : files?.[0] || files

  console.log('Selected file:', file)

  if (!file) {
    console.log('No file selected')
    return
  }

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    saveErrorMessage.value = t('student.avatar.upload.selectImage')
    // 3秒后自动隐藏错误消息
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
    return
  }

  // 检查文件大小 (限制为2MB)
  if (file.size > 2 * 1024 * 1024) {
    saveErrorMessage.value = t('student.avatar.upload.sizeExceeded')
    // 3秒后自动隐藏错误消息
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    const base64 = e.target.result.split(',')[1] // 移除数据URL前缀
    editForm.value.avatar = base64
    editForm.value.avatar_mime_type = file.type
    editForm.value.avatar_file_name = file.name
    saveErrorMessage.value = '' // 清除错误消息

    console.log('Avatar data set:', {
      avatar_length: base64?.length,
      mime_type: file.type,
      file_name: file.name
    })
  }
  reader.onerror = () => {
    saveErrorMessage.value = t('student.avatar.upload.readError')
    // 3秒后自动隐藏错误消息
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
  }
  reader.readAsDataURL(file)
}

// 移除头像
const removeAvatar = () => {
  editForm.value.avatar = ''
  editForm.value.avatar_mime_type = ''
  editForm.value.avatar_file_name = ''
}

// 新增功能的头像上传处理
const handleCreateAvatarUpload = (event) => {
  console.log('Create file upload event:', event)

  const files = event.target?.files || event
  const file = Array.isArray(files) ? files[0] : files?.[0] || files

  console.log('Selected file:', file)

  if (!file) {
    console.log('No file selected')
    return
  }

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    createErrorMessage.value = t('student.avatar.upload.selectImage')
    setTimeout(() => {
      createErrorMessage.value = ''
    }, 3000)
    return
  }

  // 检查文件大小 (限制为2MB)
  if (file.size > 2 * 1024 * 1024) {
    createErrorMessage.value = t('student.avatar.upload.sizeExceeded')
    setTimeout(() => {
      createErrorMessage.value = ''
    }, 3000)
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    const base64 = e.target.result.split(',')[1]
    createForm.value.avatar = base64
    createForm.value.avatar_mime_type = file.type
    createForm.value.avatar_file_name = file.name
    createErrorMessage.value = ''

    console.log('Create avatar data set:', {
      avatar_length: base64?.length,
      mime_type: file.type,
      file_name: file.name
    })
  }
  reader.onerror = () => {
    createErrorMessage.value = t('student.avatar.upload.readError')
    setTimeout(() => {
      createErrorMessage.value = ''
    }, 3000)
  }
  reader.readAsDataURL(file)
}

// 移除新增头像
const removeCreateAvatar = () => {
  createForm.value.avatar = ''
  createForm.value.avatar_mime_type = ''
  createForm.value.avatar_file_name = ''
}

// 编辑功能方法
const openEditDialog = (student) => {
  editingStudent.value = student
  editForm.value = {
    student_name: student.student_name || '',
    age: student.age || '',
    grade: student.grade || '',
    // 处理不同的enabled数据格式
    enabled: student.enabled === true || student.enabled === 'Y' || student.enabled === 1,
    avatar: student.avatar || '',
    avatar_mime_type: student.avatar_mime_type || '',
    avatar_file_name: student.avatar_file_name || ''
  }
  console.log('Editing student data:', student)
  console.log('Converted form data:', editForm.value)
  editDialog.value = true
}

const closeEditDialog = () => {
  editDialog.value = false
  editingStudent.value = null
  editForm.value = {
    student_name: '',
    age: '',
    grade: '',
    enabled: true,
    avatar: '',
    avatar_mime_type: '',
    avatar_file_name: ''
  }
}

// 新增功能方法
const openCreateDialog = () => {
  createForm.value = {
    student_name: '',
    age: '',
    grade: '',
    enabled: true,
    avatar: '',
    avatar_mime_type: '',
    avatar_file_name: ''
  }
  createErrorMessage.value = ''
  createDialog.value = true
}

const closeCreateDialog = () => {
  createDialog.value = false
  createForm.value = {
    student_name: '',
    age: '',
    grade: '',
    enabled: true,
    avatar: '',
    avatar_mime_type: '',
    avatar_file_name: ''
  }
  createErrorMessage.value = ''
}

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

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

    // 构建要发送的数据
    const createData = {
      student_name: createForm.value.student_name,
      grade: createForm.value.grade,
      age: createForm.value.age,
      enabled: createForm.value.enabled
    }

    // 如果有头像数据，则包含头像字段
    if (createForm.value.avatar && createForm.value.avatar_mime_type) {
      createData.avatar = createForm.value.avatar
      createData.avatar_mime_type = createForm.value.avatar_mime_type
      createData.avatar_file_name = createForm.value.avatar_file_name
      console.log('Including avatar data:', {
        avatar_length: createData.avatar?.length,
        mime_type: createData.avatar_mime_type,
        file_name: createData.avatar_file_name
      })
    } else {
      console.log('Not including avatar data')
    }

    console.log('Sending data:', { ...createData, avatar_base64: createData.avatar ? '[base64 data]' : undefined })

    // 1. 调用API创建学生
    const newStudent = await createStudent(createData)

    // 2. 创建成功后，将新学生添加到本地列表
    const studentToAdd = {
      ...newStudent,
      enabled: createForm.value.enabled ? 'Y' : 'N'
    }

    // 如果有头像数据，则添加头像信息
    if (createForm.value.avatar && createForm.value.avatar_mime_type) {
      studentToAdd.avatar = createForm.value.avatar
      studentToAdd.avatar_mime_type = createForm.value.avatar_mime_type
      studentToAdd.avatar_file_name = createForm.value.avatar_file_name
    }

    students.value.unshift(studentToAdd) // 在列表顶部添加新学生

    // 3. 显示成功消息
    successMessage.value = t('student.messages.createSuccess')
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
    closeCreateDialog()

  } catch (error) {
    console.error('Creation failed:', error)
    createErrorMessage.value = error.message || t('student.messages.createError')
    setTimeout(() => {
      createErrorMessage.value = ''
    }, 3000)
  } finally {
    isCreating.value = false
  }
}

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

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

const confirmDeleteStudent = async () => {
  if (!studentToDelete.value?.student_id) {
    console.error('Unable to get student ID')
    return
  }

  isDeleting.value = true

  try {
    console.log('Deleting student:', studentToDelete.value)

    // 1. 调用API删除学生
    await deleteStudent(studentToDelete.value.student_id)

    // 2. 从本地列表中移除学生
    const index = students.value.findIndex(s => s.student_id === studentToDelete.value.student_id)
    if (index !== -1) {
      students.value.splice(index, 1)
    }

    // 3. 显示成功消息
    successMessage.value = t('student.messages.deleteSuccess', { name: studentToDelete.value.student_name })
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)

    closeDeleteDialog()
    closeEditDialog() // 自动关闭编辑对话框

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

const saveStudent = async () => {
  if (!editingStudent.value?.student_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 saving:', editForm.value)

    // 构建要发送的数据
    const updateData = {
      student_name: editForm.value.student_name,
      grade: editForm.value.grade,
      age: editForm.value.age,
      enabled: editForm.value.enabled
    }

    // 如果有头像数据，则包含头像字段
    if (editForm.value.avatar && editForm.value.avatar_mime_type) {
      updateData.avatar = editForm.value.avatar
      updateData.avatar_mime_type = editForm.value.avatar_mime_type
      updateData.avatar_file_name = editForm.value.avatar_file_name
      console.log('Including avatar data:', {
        avatar_length: updateData.avatar?.length,
        mime_type: updateData.avatar_mime_type,
        file_name: updateData.avatar_file_name
      })
    } else {
      console.log('Not including avatar data:', {
        avatar: editForm.value.avatar,
        avatar_mime_type: editForm.value.avatar_mime_type
      })
    }

    console.log('Sending data:', { ...updateData, avatar_base64: updateData.avatar ? '[base64 data]' : undefined })

    // 1. 调用API保存到服务器
    await updateStudent(editingStudent.value.student_id, updateData)

    // 2. API调用成功后，更新本地数据
    const index = students.value.findIndex(s => s.student_id === editingStudent.value.student_id)
    if (index !== -1) {
      const updatedStudent = {
        ...students.value[index],
        student_name: editForm.value.student_name,
        grade: editForm.value.grade,
        age: editForm.value.age,
        enabled: editForm.value.enabled ? 'Y' : 'N'  // 转换为API格式
      }

      // 如果有头像数据，则更新头像信息
      if (editForm.value.avatar && editForm.value.avatar_mime_type) {
        updatedStudent.avatar = editForm.value.avatar
        updatedStudent.avatar_mime_type = editForm.value.avatar_mime_type
        updatedStudent.avatar_file_name = editForm.value.avatar_file_name
      }

      students.value[index] = updatedStudent
    }

    // 3. 显示成功消息
    successMessage.value = t('student.messages.updateSuccess')
    // 3秒后自动隐藏成功消息
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
    closeEditDialog()

  } catch (error) {
    // 4. API失败时不更新本地数据，显示错误消息
    console.error('Save failed:', error)
    saveErrorMessage.value = error.message || t('student.messages.updateError')
    // 3秒后自动隐藏错误消息
    setTimeout(() => {
      saveErrorMessage.value = ''
    }, 3000)
  } finally {
    isSaving.value = false
  }
}
</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="openCreateDialog"
        >
          {{ $t('student.buttons.addStudent') }}
        </v-btn>
        <v-btn color="primary" prepend-icon="mdi-refresh" :loading="isLoading" @click="fetchStudents">
          {{ $t('common.buttons.refresh') }}
        </v-btn>
      </v-col>
    </v-row>

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

    <!-- 成功消息 -->
    <v-alert v-if="successMessage" type="success" class="mb-4" closable @click:close="successMessage = ''">
      {{ successMessage }}
    </v-alert>

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

    <v-data-table
      :headers="headers"
      :items="students"
      item-key="student_id"
      :items-per-page="10"
      class="elevation-1"
      :sort-by="[{ key: 'student_name', order: 'asc' }]"
      multi-sort
      :items-per-page-text="$t('student.table.pagination.itemsPerPage')"
      :no-data-text="$t('student.table.pagination.noDataText')"
      :loading-text="$t('student.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('student.table.pagination.itemsPerPageAll') }
      ]"
    >
      <template v-slot:[`item.avatar`]="{ item }">
        <div class="d-flex align-center py-2">
          <v-avatar size="64">
            <template v-if="item.avatar && item.avatar_mime_type">
              <v-img
                :src="getAvatarDataUrl(item.avatar, item.avatar_mime_type)"
                :alt="item.avatar_file_name || 'avatar'"
                cover
                @error="console.warn('Avatar loading failed:', item.avatar_file_name)"
              />
            </template>
            <template v-else>
              <span class="text-body-2">{{ getAvatarFallback(item.student_name) }}</span>
            </template>
          </v-avatar>
        </div>
      </template>
      <template v-slot:[`item.enabled`]="{ item }">
        <v-chip :color="item.enabled === 'Y' ? 'success' : 'error'" size="small" variant="flat">
          {{ item.enabled === 'Y' ? $t('common.status.enabled') : $t('common.status.disabled') }}
        </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-dialog v-model="editDialog" max-width="500px">
      <v-card>
        <v-card-title class="text-h5">
          {{ $t('student.dialog.edit') }}
        </v-card-title>
        <v-card-text>
          <v-container>
            <!-- 保存错误消息 -->
            <v-alert v-if="saveErrorMessage" type="error" class="mb-4" closable @click:close="saveErrorMessage = ''">
              {{ saveErrorMessage }}
            </v-alert>

            <v-row>
              <!-- Avatar upload area -->
              <v-col cols="12">
                <div class="mb-6">
                  <h4 class="text-subtitle-1 mb-4 font-weight-medium">{{ $t('student.avatar.upload.title') }}</h4>

                  <!-- Avatar preview and upload area -->
                  <div class="d-flex flex-column align-center">
                    <!-- Avatar preview area -->
                    <div class="position-relative mb-4">
                      <v-avatar size="120" class="elevation-4">
                        <template v-if="editForm.avatar && editForm.avatar_mime_type">
                          <v-img
                            :src="getAvatarDataUrl(editForm.avatar, editForm.avatar_mime_type)"
                            :alt="editForm.avatar_file_name || $t('student.avatar.fallback.alt')"
                            cover
                          />
                        </template>
                        <template v-else>
                          <div class="d-flex flex-column align-center justify-center h-100 bg-grey-lighten-3">
                            <v-icon size="48" color="grey-darken-1">mdi-account-circle</v-icon>
                            <span class="text-caption text-grey-darken-1 mt-1">{{ getAvatarFallback(editForm.student_name) }}</span>
                          </div>
                        </template>
                      </v-avatar>

                      <!-- Remove avatar button -->
                      <v-btn
                        v-if="editForm.avatar"
                        icon="mdi-close"
                        size="small"
                        color="error"
                        variant="elevated"
                        class="position-absolute"
                        style="top: -8px; right: -8px;"
                        @click="removeAvatar"
                      />
                    </div>

                    <!-- Upload button area -->
                    <div class="d-flex flex-column align-center gap-3">
                      <!-- Hidden file input -->
                      <input
                        ref="fileInput"
                        type="file"
                        accept="image/*"
                        style="display: none;"
                        @change="handleAvatarUpload"
                      />

                      <!-- Upload button -->
                      <v-btn
                        color="primary"
                        variant="outlined"
                        size="large"
                        prepend-icon="mdi-camera-plus"
                        @click="$refs.fileInput.click()"
                        :disabled="isSaving"
                      >
                        {{ editForm.avatar ? $t('student.avatar.upload.change') : $t('student.avatar.upload.button') }}
                      </v-btn>

                      <!-- File format description -->
                      <div class="text-center">
                        <div class="text-caption text-medium-emphasis">
                          {{ $t('student.avatar.upload.formats') }}
                        </div>
                        <div class="text-caption text-medium-emphasis">
                          {{ $t('student.avatar.upload.sizeLimit') }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Divider -->
                <v-divider class="mb-4" />
              </v-col>

              <!-- Form fields -->
              <v-col cols="12">
                <v-text-field
                  v-model="editForm.student_name"
                  :label="$t('student.form.name')"
                  required
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model="editForm.age"
                  :label="$t('student.form.age')"
                  type="number"
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model="editForm.grade"
                  :label="$t('student.form.grade')"
                  variant="outlined"
                />
              </v-col>
              <v-col cols="12">
                <v-switch
                  v-model="editForm.enabled"
                  :label="$t('student.form.enabledStatus')"
                  color="primary"
                />
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-btn
            color="error"
            variant="outlined"
            prepend-icon="mdi-delete"
            @click="openDeleteDialog(editingStudent)"
            :disabled="isSaving"
          >
            {{ $t('common.buttons.delete') }}
          </v-btn>
          <v-spacer />
          <v-btn
            color="grey-darken-1"
            variant="text"
            @click="closeEditDialog"
          >
            {{ $t('common.buttons.cancel') }}
          </v-btn>
          <v-btn
            color="primary"
            variant="text"
            :loading="isSaving"
            :disabled="isSaving"
            @click="saveStudent"
          >
            {{ $t('common.buttons.save') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Add Student Dialog -->
    <v-dialog v-model="createDialog" max-width="500px">
      <v-card>
        <v-card-title class="text-h5">
          {{ $t('student.dialog.add') }}
        </v-card-title>
        <v-card-text>
          <v-container>
            <!-- Error messages -->
            <v-alert v-if="createErrorMessage" type="error" class="mb-4" closable @click:close="createErrorMessage = ''">
              {{ createErrorMessage }}
            </v-alert>

            <v-row>
              <!-- Avatar upload area -->
              <v-col cols="12">
                <div class="mb-6">
                  <h4 class="text-subtitle-1 mb-4 font-weight-medium">{{ $t('student.avatar.upload.title') }}</h4>

                  <!-- Avatar preview and upload area -->
                  <div class="d-flex flex-column align-center">
                    <!-- Avatar preview area -->
                    <div class="position-relative mb-4">
                      <v-avatar size="120" class="elevation-4">
                        <template v-if="createForm.avatar && createForm.avatar_mime_type">
                          <v-img
                            :src="getAvatarDataUrl(createForm.avatar, createForm.avatar_mime_type)"
                            :alt="createForm.avatar_file_name || $t('student.avatar.fallback.alt')"
                            cover
                          />
                        </template>
                        <template v-else>
                          <div class="d-flex flex-column align-center justify-center h-100 bg-grey-lighten-3">
                            <v-icon size="48" color="grey-darken-1">mdi-account-circle</v-icon>
                            <span class="text-caption text-grey-darken-1 mt-1">{{ getAvatarFallback(createForm.student_name) }}</span>
                          </div>
                        </template>
                      </v-avatar>

                      <!-- Remove avatar button -->
                      <v-btn
                        v-if="createForm.avatar"
                        icon="mdi-close"
                        size="small"
                        color="error"
                        variant="elevated"
                        class="position-absolute"
                        style="top: -8px; right: -8px;"
                        @click="removeCreateAvatar"
                      />
                    </div>

                    <!-- Upload button area -->
                    <div class="d-flex flex-column align-center gap-3">
                      <!-- Hidden file input -->
                      <input
                        ref="createFileInput"
                        type="file"
                        accept="image/*"
                        style="display: none;"
                        @change="handleCreateAvatarUpload"
                      />

                      <!-- Upload button -->
                      <v-btn
                        color="primary"
                        variant="outlined"
                        size="large"
                        prepend-icon="mdi-camera-plus"
                        @click="$refs.createFileInput.click()"
                        :disabled="isCreating"
                      >
                        {{ createForm.avatar ? $t('student.avatar.upload.change') : $t('student.avatar.upload.button') }}
                      </v-btn>

                      <!-- File format description -->
                      <div class="text-center">
                        <div class="text-caption text-medium-emphasis">
                          {{ $t('student.avatar.upload.formats') }}
                        </div>
                        <div class="text-caption text-medium-emphasis">
                          {{ $t('student.avatar.upload.sizeLimit') }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Divider -->
                <v-divider class="mb-4" />
              </v-col>

              <!-- Form fields -->
              <v-col cols="12">
                <v-text-field
                  v-model="createForm.student_name"
                  :label="$t('student.form.name') + ' *'"
                  required
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model="createForm.age"
                  :label="$t('student.form.age')"
                  type="number"
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model="createForm.grade"
                  :label="$t('student.form.grade')"
                  variant="outlined"
                />
              </v-col>
              <v-col cols="12">
                <v-switch
                  v-model="createForm.enabled"
                  :label="$t('student.form.enabledStatus') + ' *'"
                  color="primary"
                />
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn
            color="grey-darken-1"
            variant="text"
            @click="closeCreateDialog"
          >
            {{ $t('common.buttons.cancel') }}
          </v-btn>
          <v-btn
            color="success"
            variant="text"
            :loading="isCreating"
            :disabled="isCreating"
            @click="createNewStudent"
          >
            {{ $t('common.buttons.create') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Delete Confirmation 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('student.dialog.delete') }}
        </v-card-title>
        <v-card-text>
          <div class="text-body-1 mb-4">
            {{ $t('student.deleteConfirmation.message') }}
          </div>
          <div v-if="studentToDelete" class="bg-grey-lighten-4 pa-3 rounded">
            <div class="d-flex align-center mb-2">
              <v-avatar size="40" class="mr-3">
                <template v-if="studentToDelete.avatar && studentToDelete.avatar_mime_type">
                  <v-img
                    :src="getAvatarDataUrl(studentToDelete.avatar, studentToDelete.avatar_mime_type)"
                    :alt="studentToDelete.avatar_file_name || 'avatar'"
                    cover
                  />
                </template>
                <template v-else>
                  <span class="text-body-2">{{ getAvatarFallback(studentToDelete.student_name) }}</span>
                </template>
              </v-avatar>
              <div>
                <div class="font-weight-medium">{{ studentToDelete.student_name }}</div>
                <div class="text-caption text-medium-emphasis">
                  {{ studentToDelete.age }} years old | {{ studentToDelete.grade }}
                </div>
              </div>
            </div>
          </div>
          <div class="text-body-2 text-error mt-4">
            <v-icon icon="mdi-alert-circle" size="small" class="mr-1" />
            {{ $t('student.deleteConfirmation.warning') }}
          </div>
        </v-card-text>
        <v-card-actions>
          <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"
            :loading="isDeleting"
            :disabled="isDeleting"
            @click="confirmDeleteStudent"
          >
            {{ $t('common.buttons.confirm') + ' ' + $t('common.buttons.delete') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>

</template>

<style scoped>
</style>


