<script setup>
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { fromApiBool } from '@/api/boolCodec.js'
import { createStudent, updateStudent } from '@/api/studentService.js'
import StudentAvatarUpload from '@/components/student/StudentAvatarUpload.vue'
import StudentSliderIconUpload from '@/components/student/StudentSliderIconUpload.vue'

// Create / edit dialog. `student` prop null → create mode, object → edit.
// Owns the 11-field form (4 base + avatar trio + slider-icon trio), the
// two upload sub-components, validation, save flow, and inline error.
// Delete was spun out to StudentDeleteDialog (delete flow is now
// row-triggered — the old edit-dialog delete button is gone).
const props = defineProps({
  open: { type: Boolean, default: false },
  student: { type: Object, default: null },
})
const emit = defineEmits(['close', 'saved'])

const { t } = useI18n()

const isCreateMode = ref(false)
const editingStudent = ref(null)
const editForm = ref({
  student_name: '',
  age: '',
  grade: '',
  enabled: true,
  avatar: '',
  avatar_mime_type: '',
  avatar_file_name: '',
  slider_icon: '',
  slider_icon_mime_type: '',
  slider_icon_file_name: '',
})
const isSaving = ref(false)
const isError = ref(false)
const errorMessage = ref('')
const uploadError = ref('')

const blankForm = () => ({
  student_name: '',
  age: '',
  grade: '',
  enabled: true,
  avatar: '',
  avatar_mime_type: '',
  avatar_file_name: '',
  slider_icon: '',
  slider_icon_mime_type: '',
  slider_icon_file_name: '',
})

function resetForm() {
  editForm.value = blankForm()
  uploadError.value = ''
}

function loadFromStudent(s) {
  isCreateMode.value = false
  editingStudent.value = s
  editForm.value = {
    student_name: s.student_name || '',
    age: s.age ?? '',
    grade: s.grade || '',
    enabled: fromApiBool(s.enabled),
    avatar: s.avatar || '',
    avatar_mime_type: s.avatar_mime_type || '',
    avatar_file_name: s.avatar_file_name || '',
    slider_icon: s.slider_icon || '',
    slider_icon_mime_type: s.slider_icon_mime_type || '',
    slider_icon_file_name: s.slider_icon_file_name || '',
  }
}

function initCreate() {
  isCreateMode.value = true
  editingStudent.value = null
  resetForm()
}

function closeDialog() {
  isError.value = false
  errorMessage.value = ''
  uploadError.value = ''
  resetForm()
  emit('close')
}

function buildPayload() {
  const payload = {
    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) {
    payload.avatar = editForm.value.avatar
    payload.avatar_mime_type = editForm.value.avatar_mime_type
    payload.avatar_file_name = editForm.value.avatar_file_name
  }
  if (editForm.value.slider_icon && editForm.value.slider_icon_mime_type) {
    payload.slider_icon = editForm.value.slider_icon
    payload.slider_icon_mime_type = editForm.value.slider_icon_mime_type
    payload.slider_icon_file_name = editForm.value.slider_icon_file_name
  }
  return payload
}

async function save() {
  if (!editForm.value.student_name) {
    isError.value = true
    errorMessage.value = t('student.validation.nameRequired')
    return
  }

  isSaving.value = true
  isError.value = false
  errorMessage.value = ''

  try {
    const payload = buildPayload()
    let result
    if (isCreateMode.value) {
      result = await createStudent(payload)
    } else {
      if (!editingStudent.value?.student_id) {
        throw new Error(t('common.messages.error.general'))
      }
      result = await updateStudent(editingStudent.value.student_id, payload)
    }

    closeDialog()
    emit('saved', result)
  } catch (error) {
    console.error('Student save failed:', error)
    isError.value = true
    errorMessage.value = error?.message || t('common.messages.error.general')
  } finally {
    isSaving.value = false
  }
}

watch(
  () => [props.open, props.student],
  ([isOpen, student]) => {
    if (!isOpen) return
    isError.value = false
    errorMessage.value = ''
    uploadError.value = ''
    if (student) loadFromStudent(student)
    else initCreate()
  },
  { immediate: true },
)

function onUploadError(message) {
  uploadError.value = message
}
</script>

<template>
  <v-dialog :model-value="open" max-width="500px" @update:model-value="(v) => !v && closeDialog()">
    <v-card>
      <v-card-title>
        {{ isCreateMode ? t('student.dialog.add') : t('student.dialog.edit') }}
      </v-card-title>
      <v-card-text>
        <v-alert
          v-if="isError"
          type="error"
          variant="tonal"
          class="mb-4"
          closable
          @click:close="isError = false"
        >
          {{ errorMessage }}
        </v-alert>
        <v-alert
          v-if="uploadError"
          type="warning"
          variant="tonal"
          class="mb-4"
          closable
          @click:close="uploadError = ''"
        >
          {{ uploadError }}
        </v-alert>

        <v-form @submit.prevent="save">
          <v-container>
            <v-row>
              <!-- Avatar upload section -->
              <v-col cols="12">
                <div class="mb-6">
                  <h4 class="text-subtitle-1 mb-4 font-weight-medium">
                    {{ t('student.avatar.upload.title') }}
                  </h4>
                  <StudentAvatarUpload
                    :avatar="editForm.avatar"
                    :avatar-mime-type="editForm.avatar_mime_type"
                    :avatar-file-name="editForm.avatar_file_name"
                    :student-name="editForm.student_name"
                    :disabled="isSaving"
                    @update:avatar="(v) => (editForm.avatar = v)"
                    @update:avatar-mime-type="(v) => (editForm.avatar_mime_type = v)"
                    @update:avatar-file-name="(v) => (editForm.avatar_file_name = v)"
                    @error="onUploadError"
                  />
                </div>

                <!-- Slider icon upload section -->
                <div class="mb-4">
                  <h4 class="text-subtitle-1 mb-3 font-weight-medium">
                    {{ t('student.sliderIcon.upload.title') }}
                  </h4>
                  <StudentSliderIconUpload
                    :slider-icon="editForm.slider_icon"
                    :slider-icon-mime-type="editForm.slider_icon_mime_type"
                    :slider-icon-file-name="editForm.slider_icon_file_name"
                    :disabled="isSaving"
                    @update:slider-icon="(v) => (editForm.slider_icon = v)"
                    @update:slider-icon-mime-type="(v) => (editForm.slider_icon_mime_type = v)"
                    @update:slider-icon-file-name="(v) => (editForm.slider_icon_file_name = v)"
                    @error="onUploadError"
                  />
                </div>

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

              <!-- Base 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.number="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"
                  :true-value="true"
                  :false-value="false"
                  inset
                />
              </v-col>
            </v-row>
          </v-container>
        </v-form>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn
          color="grey-darken-1"
          variant="text"
          :disabled="isSaving"
          @click="closeDialog"
        >
          {{ t('common.buttons.cancel') }}
        </v-btn>
        <v-btn
          :color="isCreateMode ? 'success' : 'primary'"
          variant="text"
          :loading="isSaving"
          :disabled="isSaving"
          @click="save"
        >
          {{ isCreateMode ? t('common.buttons.create') : t('common.buttons.save') }}
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>