<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden" style="width: 520px; max-width: 90vw">
      <DefaultDialogHeader title="Nova Conta" @close="onDialogCancel" />
      <q-form ref="formRef" @submit="onOKClick">
        <q-card-section class="row q-col-gutter-sm q-pt-none">
          <DefaultInput
            v-model="form.code"
            v-model:error="validationErrors.code"
            :rules="[inputRules.required]"
            label="Código"
            placeholder="5.1"
            class="col-12 col-md-4"
          />

          <DefaultInput
            v-model="form.description"
            v-model:error="validationErrors.description"
            :rules="[inputRules.required]"
            label="Nome da Conta"
            placeholder="Ex. Receita de Eventos"
            class="col-12 col-md-8"
          />

          <DefaultInput
            v-model="form.chart_type"
            v-model:error="validationErrors.chart_type"
            :rules="[inputRules.required]"
            label="Tipo de Conta"
            placeholder="Ex. Ativo, Passivo, Receitas, Despesas"
            class="col-12"
          />
        </q-card-section>

        <q-card-actions align="right">
          <q-btn outline color="negative" label="Cancelar" @click="onDialogCancel" />
          <q-btn color="primary" label="Salvar" 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 { createFinancialPlanAccount } from "src/api/financial_plan_account";

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

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

const { inputRules } = useInputRules();

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

const formRef = ref(null);

const form = ref({
  code: "",
  description: "",
  chart_type: "",
});

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

const onOKClick = async () => {
  await submitForm(() =>
    createFinancialPlanAccount({
      code: form.value.code,
      description: form.value.description,
      chart_type: form.value.chart_type,
    }),
  );
};
</script>
