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

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

            <q-file
              v-model="selectedFile"
              :error="!!validationErrors.file"
              :error-message="validationErrors.file"
              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-scroll-area>

        <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>
      </DefaultForm>
    </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, validationErrors, 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>
