<script setup>
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'

// Avatar upload sub-component. Owns the FileReader, mime check, and 2MB
// size cap. Reports errors via @error event so the parent dialog can
// surface them in its own alert. Updates parent state via v-model
// (avatar / avatarMimeType / avatarFileName).
const props = defineProps({  // eslint-disable-line no-unused-vars
  avatar: { type: String, default: '' },
  avatarMimeType: { type: String, default: '' },
  avatarFileName: { type: String, default: '' },
  studentName: { type: String, default: '' },
  disabled: { type: Boolean, default: false },
})
const emit = defineEmits([
  'update:avatar',
  'update:avatarMimeType',
  'update:avatarFileName',
  'error',
])

const { t } = useI18n()
const fileInput = ref(null)

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 handleUpload(event) {
  const files = event.target?.files || event
  const file = Array.isArray(files) ? files[0] : files?.[0] || files
  if (!file) return

  if (!file.type.startsWith('image/')) {
    emit('error', t('student.avatar.upload.selectImage'))
    return
  }
  if (file.size > 2 * 1024 * 1024) {
    emit('error', t('student.avatar.upload.sizeExceeded'))
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    const base64 = e.target.result.split(',')[1]
    emit('update:avatar', base64)
    emit('update:avatarMimeType', file.type)
    emit('update:avatarFileName', file.name)
    emit('error', '')
  }
  reader.onerror = () => emit('error', t('student.avatar.upload.readError'))
  reader.readAsDataURL(file)
}

function remove() {
  emit('update:avatar', '')
  emit('update:avatarMimeType', '')
  emit('update:avatarFileName', '')
}

function trigger() {
  fileInput.value?.click()
}
</script>

<template>
  <div class="d-flex flex-column align-center">
    <div class="position-relative mb-4">
      <v-avatar size="120" class="elevation-4">
        <template v-if="avatar && avatarMimeType">
          <v-img
            :src="getAvatarDataUrl(avatar, avatarMimeType)"
            :alt="avatarFileName || 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(studentName)
            }}</span>
          </div>
        </template>
      </v-avatar>
      <v-btn
        v-if="avatar"
        icon="mdi-close"
        size="small"
        color="error"
        variant="elevated"
        class="position-absolute"
        style="top: -8px; right: -8px"
        :disabled="disabled"
        @click="remove"
      />
    </div>

    <div class="d-flex flex-column align-center gap-3">
      <input
        ref="fileInput"
        type="file"
        accept="image/*"
        style="display: none"
        @change="handleUpload"
      />
      <v-btn
        color="primary"
        variant="outlined"
        size="large"
        prepend-icon="mdi-camera-plus"
        :disabled="disabled"
        @click="trigger"
      >
        {{ avatar ? t('student.avatar.upload.change') : t('student.avatar.upload.button') }}
      </v-btn>
      <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>
</template>