<script setup>
import { onMounted, ref } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { getStudents } from '@/api/studentService.js'

const authStore = useAuthStore()

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

const headers = [
  { title: 'Avatar', value: 'avatar', align: 'start' },
  { title: 'Name', value: 'student_name' },
  { title: 'Enabled', value: 'enabled_flag' },
  { title: 'Age', value: 'age' },
  { title: 'Grade', value: 'grade' },
]

const fetchStudents = async () => {
  isLoading.value = true
  isError.value = false
  errorMessage.value = ''
  try {
    const data = await getStudents()
    students.value = Array.isArray(data) ? data : (data?.items || [])
  } catch (e) {
    isError.value = true
    errorMessage.value = e?.response?.data?.detail || e?.message || 'Failed to load students'
  } 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() : '?'
}
</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">Students</h2>
      </v-col>
      <v-col cols="12" sm="6" class="text-sm-right text-right">
        <v-btn color="primary" prepend-icon="mdi-refresh" :loading="isLoading" @click="fetchStudents">
          Refresh
        </v-btn>
      </v-col>
    </v-row>

    <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="students" item-key="id" :items-per-page="-1" class="elevation-1">
      <template v-slot:[`item.avatar`]="{ item }">
        <v-avatar size="36">
          <template v-if="item.avatar">
            <v-img :src="item.avatar" alt="avatar" cover></v-img>
          </template>
          <template v-else>
            <span>{{ getAvatarFallback(item.student_name) }}</span>
          </template>
        </v-avatar>
      </template>
      <template v-slot:[`item.enabled_flag`]="{ item }">
        <v-chip :color="item.enabled_flag ? 'success' : 'error'" size="small" variant="flat">
          {{ item.enabled_flag ? 'Enabled' : 'Disabled' }}
        </v-chip>
      </template>
    </v-data-table>
  </v-container>

</template>

<style scoped>
</style>


