<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden" style="width: 560px; max-width: 95vw">
      <DefaultDialogHeader
        :title="history ? 'Editar Histórico' : 'Novo Histórico'"
        @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-input
              v-model="form.content"
              label="Conteúdo"
              outlined
              type="textarea"
              rows="5"
              autogrow
            />
            <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="history ? 'Salvar' : '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 { createHistory, updateHistory } from "src/api/unit_history";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";

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

const { history, unitId } = defineProps({
  history: { type: Object, default: null },
  unitId: { type: Number, required: true },
});

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

const formRef = ref(null);

const form = ref({
  title: history?.title ?? "",
  content: history?.content ?? "",
  visible_to_franchisee: history?.visible_to_franchisee ?? false,
});

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

async function onOKClick() {
  await execute(() => {
    const payload = {
      unit_id: unitId,
      title: form.value.title,
      content: form.value.content,
      visible_to_franchisee: form.value.visible_to_franchisee,
    };

    return history ? updateHistory(history.id, payload) : createHistory(payload);
  });
}
</script>
