<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin" style="width: 480px; max-width: 95vw">
      <DefaultDialogHeader title="Adicionar 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"
              outlined
              accept="image/*,video/*,.pdf"
              :rules="[inputRules.required]"
            >
              <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="Adicionar" 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 { createStudentMedia } 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 { studentId } = defineProps({
  studentId: { type: Number, required: true },
});

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

const formRef = ref(null);
const selectedFile = ref(null);
const form = ref({ 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", studentId);
    formData.append("file", selectedFile.value);
    return createStudentMedia(formData);
  });
}
</script>
