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

      <DefaultForm
        ref="formRef"
        @submit="onOKClick"
      >
        <q-scroll-area
          ref="scrollAreaRef"
          class="dialog-form-scroll dialog-form-scroll--sm"
        >
          <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]"
              />

              <DefaultInput
                v-model="form.content"
                v-model:error="validationErrors.content"
                autogrow
                label="Conteúdo"
                outlined
                rows="5"
                type="textarea"
              />

              <q-toggle
                v-model="form.visible_to_franchisee"
                color="positive"
                label="Visível ao franqueado"
              />
            </div>
          </q-card-section>
        </q-scroll-area>

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

          <q-btn
            color="primary"
            no-caps
            type="submit"
            :label="history ? 'Salvar' : 'Adicionar'"
            :loading="loading"
          />
        </q-card-actions>
      </DefaultForm>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { createHistory, updateHistory } from "src/api/unit_history";
import { useDialogPluginComponent } from "quasar";
import { useForm } from "src/composables/useForm";
import { useInputRules } from "src/composables/useInputRules";
import { useScroll } from "src/composables/useScroll";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { useTemplateRef } from "vue";

import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultForm from "src/components/defaults/DefaultForm.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 { dialogRef, onDialogHide, onDialogOK, onDialogCancel } =
  useDialogPluginComponent();

const { inputRules } = useInputRules();
const { scrollToComponent } = useScroll();

const formRef = useTemplateRef("formRef");
const scrollAreaRef = useTemplateRef("scrollAreaRef");

const dialogTitle = history
  ? "Editar Histórico"
  : "Novo Histórico";

const { form, getUpdatedFields } = useForm({
  content: history?.content ?? "",
  title: history?.title ?? "",

  visible_to_franchisee:
    history?.visible_to_franchisee ?? false,
});

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

const onOKClick = async () => {
  await execute(() => {
    if (history) {
      return updateHistory(
        history.id,
        { ...getUpdatedFields.value },
      );
    }

    return createHistory({
      content: form.content,
      title: form.title,
      unit_id: unitId,

      visible_to_franchisee:
        form.visible_to_franchisee,
    });
  });
};
</script>