<script setup>
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useDisplay } from 'vuetify'

// Presentation-only table for terms. `student_name` is denormalized
// client-side via the parent's mapRow — items arrive pre-joined.
// Emits edit / delete events; parent owns the open-dialog state.
defineProps({
  items: { type: Array, required: true },
})
const emit = defineEmits(['edit', 'delete'])

const { xs } = useDisplay()
const { t } = useI18n()

// Format ISO date string for table display. Preserves zh-CN locale to
// match pre-refactor behaviour (intentional — see plan risk #11).
function formatDate(dateString) {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const headers = computed(() => [
  { title: t('term.table.headers.termName'), value: 'term_name', sortable: true },
  { title: t('term.table.headers.studentName'), value: 'student_name', sortable: true },
  { title: t('term.table.headers.startDate'), value: 'term_start_date', sortable: true },
  { title: t('term.table.headers.endDate'), value: 'term_end_date', sortable: true },
  { title: t('term.table.headers.actions'), value: 'actions', sortable: false, align: 'end' },
])
</script>

<template>
  <v-data-table
    :headers="headers"
    :items="items"
    item-key="term_id"
    :items-per-page="10"
    class="elevation-1 text-no-wrap"
    :sort-by="[{ key: 'term_start_date', order: 'desc' }]"
    multi-sort
    :items-per-page-text="t('term.table.pagination.itemsPerPage')"
    :no-data-text="t('term.table.pagination.noDataText')"
    :loading-text="t('term.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('term.table.pagination.itemsPerPageAll') },
    ]"
    :hide-default-footer="false"
    :height="xs ? undefined : 'calc(100dvh - 360px)'"
    :fixed-header="!xs"
    :density="xs ? 'compact' : 'comfortable'"
  >
    <template v-slot:[`item.term_start_date`]="{ item }">
      {{ formatDate(item.term_start_date) }}
    </template>
    <template v-slot:[`item.term_end_date`]="{ item }">
      {{ formatDate(item.term_end_date) }}
    </template>
    <template v-slot:[`item.actions`]="{ item }">
      <v-btn
        icon="mdi-pencil"
        size="small"
        color="primary"
        variant="text"
        @click="emit('edit', item)"
      >
      </v-btn>
      <v-btn
        icon="mdi-delete"
        size="small"
        color="error"
        variant="text"
        @click="emit('delete', item)"
      >
      </v-btn>
    </template>
  </v-data-table>
</template>

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