<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"
              label="Título"
              outlined
              :rules="[inputRules.required]"
            />

            <q-file
              v-model="selectedFile"
              label="Arquivo"
              outlined
              accept="image/*,video/*,.pdf"
              :rules="[inputRules.required]"
            >
              <template #prepend>
                <q-icon name="attach_file" />
              </template>
            </q-file>

            <q-toggle
              v-model="form.visible_to_franchisee"
              label="Visível ao franqueado"
              color="positive"
            />
          </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-2" 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 { createMedia } from "src/api/unit_media";
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: false,
});

const { loading, 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", form.value.visible_to_franchisee ? 1 : 0);
    return createMedia(formData);
  });
}
</script>
