<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden" style="width: 520px; max-width: 90vw">
      <DefaultDialogHeader :title="title" @close="onDialogCancel" />
      <q-form ref="formRef" @submit="onOKClick">
        <q-card-section class="row q-col-gutter-sm q-pt-none">
          <DefaultSelect
            v-model="form.transaction_type"
            v-model:error="validationErrors.transaction_type"
            :options="typeOptions"
            emit-value
            map-options
            :rules="[inputRules.required]"
            label="Tipo"
            placeholder="Entrada ou Saída"
            class="col-12"
          />

          <DefaultInput
            v-model="form.description"
            v-model:error="validationErrors.description"
            :rules="[inputRules.required]"
            label="Descrição"
            placeholder="Descreva a movimentação"
            class="col-12"
          />

          <DefaultSelect
            v-model="form.financial_plan_account_id"
            v-model:error="validationErrors.financial_plan_account_id"
            :options="planAccountOptions"
            :loading="loadingPlanAccounts"
            emit-value
            map-options
            use-input
            input-debounce="0"
            :rules="[inputRules.required]"
            label="Plano de Contas"
            placeholder="Selecione a conta"
            class="col-12"
            @filter="filterPlanAccounts"
          />

          <DefaultCurrencyInput
            v-model="form.amount"
            v-model:error="validationErrors.amount"
            label="Valor"
            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, onMounted } from "vue";
import { useDialogPluginComponent } from "quasar";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { createTreasuryLaunch } from "src/api/treasury_launch";
import { getFinancialPlanAccounts } from "src/api/financial_plan_account";

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

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

const { account } = defineProps({
  account: {
    type: Object,
    required: true,
  },
});

const { inputRules } = useInputRules();

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

const formRef = ref(null);
const title = `Nova movimentação — ${account.name}`;

const typeOptions = [
  { label: "Entrada", value: "entrada" },
  { label: "Saída", value: "saida" },
];

const form = ref({
  transaction_type: null,
  description: "",
  financial_plan_account_id: null,
  amount: 0,
});

const allPlanAccounts = ref([]);
const planAccountOptions = ref([]);
const loadingPlanAccounts = ref(false);

const filterPlanAccounts = (needle, update) => {
  update(() => {
    const term = needle.toLowerCase();
    planAccountOptions.value = term
      ? allPlanAccounts.value.filter((o) => o.label.toLowerCase().includes(term))
      : allPlanAccounts.value;
  });
};

onMounted(async () => {
  loadingPlanAccounts.value = true;
  try {
    const accounts = await getFinancialPlanAccounts();
    allPlanAccounts.value = accounts.map((a) => ({
      label: `${a.code} - ${a.description}`,
      value: a.id,
    }));
    planAccountOptions.value = allPlanAccounts.value;
  } finally {
    loadingPlanAccounts.value = false;
  }
});

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

const onOKClick = async () => {
  await submitForm(() =>
    createTreasuryLaunch({
      account_id: account.id,
      transaction_type: form.value.transaction_type,
      description: form.value.description,
      financial_plan_account_id: form.value.financial_plan_account_id,
      amount: form.value.amount,
    }),
  );
};
</script>
