<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin" style="width: 480px; max-width: 95vw">
      <DefaultDialogHeader title="Editar Mídia" @close="onDialogCancel" />

      <q-form ref="formRef" @submit="onSubmit">
        <q-card-section class="q-pt-none">
          <div class="column q-gutter-sm">
            <DefaultInput
              v-model="form.name"
              label="Nome do documento"
              :rules="[inputRules.required]"
            />

            <q-file
              v-model="selectedFile"
              label="Arquivo (opcional)"
              outlined
              accept="image/*,video/*,.pdf"
              clearable
            >
              <template #prepend>
                <q-icon name="mdi-paperclip" />
              </template>
            </q-file>
          </div>
        </q-card-section>

        <q-card-actions align="right" class="q-pa-md">
          <q-btn outline color="primary" label="Cancelar" @click="onDialogCancel" />
          <q-btn color="primary" label="Salvar" type="submit" :loading="loading" />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref } from "vue";
import { useDialogPluginComponent } from "quasar";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { updateStudentMedia } from "src/api/student_media";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";

defineEmits([...useDialogPluginComponent.emits]);

const { media } = defineProps({
  media: { type: Object, required: true },
});

const { inputRules } = useInputRules();
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();

const formRef = ref(null);
const selectedFile = ref(null);
const form = ref({ name: media.name ?? "" });

const { loading, execute } = useSubmitHandler({
  formRef,
  onSuccess: (result) => onDialogOK(result),
});

async function onSubmit() {
  await execute(() => {
    const formData = new FormData();
    formData.append("name", form.value.name);
    formData.append("student_id", media.student_id);
    if (selectedFile.value) {
      formData.append("file", selectedFile.value);
    }
    return updateStudentMedia(media.id, formData);
  });
}
</script>
