<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin dialog-form-card treasury-dialog-card">
      <DefaultDialogHeader
        :title="title"
        @close="onDialogCancel"
      />

      <DefaultForm
        ref="formRef"
        @submit="onOKClick"
      >
        <q-scroll-area
          ref="scrollAreaRef"
          class="dialog-form-scroll dialog-form-scroll--sm"
        >
          <q-card-section class="row q-col-gutter-md q-px-lg q-pt-md q-pb-sm">
            <DefaultInput
              v-model="form.name"
              v-model:error="validationErrors.name"
              class="col-12"
              label="Nome (ex.: Banco do Brasil, Caixa Loja)"
              outlined
              :rules="[inputRules.required, optionalMaxLengthRule(255)]"
            />

            <DefaultInput
              v-model="form.bank_name"
              v-model:error="validationErrors.bank_name"
              class="col-12 col-sm-6"
              label="Banco"
              outlined
              :rules="[optionalMaxLengthRule(255)]"
            />

            <DefaultInput
              v-model="form.bank_agency"
              v-model:error="validationErrors.bank_agency"
              class="col-12 col-sm-6"
              label="Agência"
              outlined
              :rules="[optionalMaxLengthRule(50)]"
            />

            <DefaultInput
              v-model="form.bank_account"
              v-model:error="validationErrors.bank_account"
              class="col-12 col-sm-6"
              label="Conta"
              outlined
              :rules="[optionalMaxLengthRule(50)]"
            />

            <DefaultSelect
              v-model="form.bank_type_account"
              v-model:error="validationErrors.bank_type_account"
              class="col-12 col-sm-6"
              emit-value
              label="Tipo"
              map-options
              outlined
              :options="accountTypeOptions"
            />
          </q-card-section>
        </q-scroll-area>

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

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

<script setup>
import { computed, useTemplateRef } from "vue";

import {
  createTreasuryAccountMe,
  updateTreasuryAccountMe,
} from "src/api/treasury";

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 DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultForm from "src/components/defaults/DefaultForm.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

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

const props = defineProps({
  account: {
    type: Object,
    default: null,
  },
});

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

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

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

const isEdit = computed(() => !!props.account?.id);

const title = computed(() =>
  isEdit.value ? "Editar conta" : "Nova conta",
);

const accountTypeOptions = [
  {
    label: "Corrente",
    value: "corrente",
  },
  {
    label: "Poupança",
    value: "poupanca",
  },
];

const { form, getUpdatedFields } = useForm({
  bank_account: props.account?.bank_account ?? "",
  bank_agency: props.account?.bank_agency ?? "",
  bank_name: props.account?.bank_name ?? "",
  bank_type_account: props.account?.bank_type_account ?? null,
  name: props.account?.name ?? "",
  treasury_type: "bank",
});

const optionalMaxLengthRule = (max) => (value) =>
  !value ||
  String(value).length <= max ||
  `Informe no máximo ${max} caracteres.`;

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

const onOKClick = async () => {
  await execute(() => {
    if (isEdit.value) {
      return updateTreasuryAccountMe(
        props.account.id,
        { ...getUpdatedFields.value },
      );
    }

    return createTreasuryAccountMe({ ...form });
  });
};
</script>

<style scoped>
.treasury-dialog-card {
  width: 520px;
  max-width: calc(100vw - 32px);
}
</style>