<script setup>
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { deleteStudent } from '@/api/studentService.js'

// Delete-confirmation dialog. Owns the deleteStudent API call, isDeleting
// state, and inline error display (the cross-dialog error bug — delete
// errors used to surface in the edit dialog's alert; now they appear
// here). Parent passes the student to delete via the `student` prop; we
// emit `@deleted(id)` on success and `@close` on cancel/after success.
const props = defineProps({
  open: { type: Boolean, default: false },
  student: { type: Object, default: null },
})
const emit = defineEmits(['close', 'deleted'])

const { t } = useI18n()

const isDeleting = ref(false)
const isError = ref(false)
const errorMessage = ref('')

function getAvatarDataUrl(avatar, mimeType) {
  if (!avatar || !mimeType) return null
  return `data:${mimeType};base64,${avatar}`
}
function getAvatarFallback(name) {
  if (!name || typeof name !== 'string') return '?'
  const trimmed = name.trim()
  return trimmed ? trimmed.charAt(0).toUpperCase() : '?'
}

function close() {
  if (isDeleting.value) return
  emit('close')
}

async function confirm() {
  if (!props.student?.student_id) return
  isDeleting.value = true
  isError.value = false
  errorMessage.value = ''
  try {
    await deleteStudent(props.student.student_id)
    emit('deleted', props.student.student_id)
    emit('close')
  } catch (error) {
    console.error('Student deletion failed:', error)
    isError.value = true
    errorMessage.value = error?.message || t('student.messages.deleteError')
  } finally {
    isDeleting.value = false
  }
}
</script>

<template>
  <v-dialog :model-value="open" max-width="400px" @update:model-value="(v) => !v && close()">
    <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="student" class="bg-grey-lighten-4 pa-3 rounded d-flex align-center">
          <v-avatar size="48" class="mr-3">
            <template v-if="student.avatar && student.avatar_mime_type">
              <v-img
                :src="getAvatarDataUrl(student.avatar, student.avatar_mime_type)"
                :alt="student.avatar_file_name || t('student.avatar.fallback.alt')"
                cover
              />
            </template>
            <template v-else>
              <span class="text-body-2">{{ getAvatarFallback(student.student_name) }}</span>
            </template>
          </v-avatar>
          <div>
            <div class="font-weight-medium">{{ student.student_name }}</div>
            <div class="text-caption text-medium-emphasis">
              {{ t('student.deleteConfirmation.studentInfo', {
                name: student.student_name,
                age: student.age ?? '',
                grade: student.grade ?? '',
              }) }}
            </div>
          </div>
        </div>
        <v-alert
          v-if="isError"
          type="error"
          variant="tonal"
          class="mt-4"
          closable
          @click:close="isError = false"
        >
          {{ errorMessage }}
        </v-alert>
        <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"
          :disabled="isDeleting"
          @click="close"
        >
          {{ t('common.buttons.cancel') }}
        </v-btn>
        <v-btn
          color="error"
          variant="elevated"
          prepend-icon="mdi-delete"
          :loading="isDeleting"
          :disabled="isDeleting"
          @click="confirm"
        >
          {{ t('common.buttons.confirm') + ' ' + t('common.buttons.delete') }}
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>