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

      <q-form ref="formRef" @submit="onOKClick">
        <q-card-section class="q-pt-none">
          <div class="column q-gutter-sm">
            <DefaultInput
              v-model="form.title"
              v-model:error="validationErrors.title"
              label="Título"
              outlined
              :rules="[inputRules.required]"
            />

            <q-file
              v-model="selectedFile"
              accept="image/*,video/*,.pdf"
              label="Arquivo"
              outlined
              :error="!!validationErrors.file"
              :error-message="validationErrors.file"
              :rules="[inputRules.required]"
              @update:model-value="validationErrors.file = null"
            >
              <template #prepend>
                <q-icon name="attach_file" />
              </template>
            </q-file>
          </div>
        </q-card-section>

        <q-card-actions align="right" class="q-pa-md">
          <q-btn
            color="primary"
            label="Cancelar"
            outline
            @click="onDialogCancel"
          />

          <q-btn
            color="primary-2"
            label="Adicionar"
            type="submit"
            :loading="loading"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { createMedia } from "src/api/unit_media";
import { ref } from "vue";
import { useDialogPluginComponent } from "quasar";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";

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

const { unitId } = defineProps({
  unitId: { type: Number, required: true },
});

const { inputRules } = useInputRules();

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

const formRef = ref(null);
const selectedFile = ref(null);
const form = ref({
  title: "",
  visible_to_franchisee: true,
});

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

async function onOKClick() {
  await execute(() => {
    const formData = new FormData();

    formData.append("unit_id", unitId);
    formData.append("title", form.value.title);
    formData.append("file", selectedFile.value);
    formData.append("visible_to_franchisee", 1);

    return createMedia(formData);
  });
}
</script>
