<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 a receber" @close="onDialogCancel" />

      <q-form ref="formRef" @submit.prevent="onSubmit">
        <q-card-section class="row q-col-gutter-md q-pt-none">
          <DefaultInput
            v-model="form.history"
            label="Descrição"
            class="col-12"
            lazy-rules="ondemand"
            :rules="[(value) => !!value || 'Informe a descrição']"
          />

          <div class="col-12">
            <div class="text-caption text-grey-8 q-mb-xs">Tipo da conta</div>
            <q-option-group
              v-model="form.account_type"
              :options="accountTypeOptions"
              color="primary"
              inline
              type="radio"
            />
          </div>

          <UnitSelect
            v-if="form.account_type === 'unit'"
            v-model="form.unit"
            label="Unidade"
            class="col-12"
            :rules="[(value) => !!value || 'Selecione a unidade']"
          />

          <DefaultCurrencyInput
            v-model="form.value"
            label="Valor"
            class="col-12 col-sm-6"
            lazy-rules="ondemand"
            :rules="[() => Number(form.value) > 0 || 'Informe o valor']"
          />

          <DefaultInputDatePicker
            v-model="form.due_date"
            v-model:untreated-date="form.due_date_iso"
            label="Data de vencimento"
            class="col-12 col-sm-6"
            lazy-rules="ondemand"
            :rules="[(value) => !!value || 'Informe o vencimento']"
          />

          <DefaultSelect
            v-model="form.financial_plan_account_id"
            label="Plano de contas"
            :options="planAccountOptions"
            class="col-12"
            clearable
            emit-value
            map-options
            :loading="loadingPlanAccounts"
          />

          <DefaultInput
            v-model="form.obs"
            label="Observação"
            type="textarea"
            class="col-12"
            rows="3"
          />
        </q-card-section>

        <q-separator />
        <q-card-actions align="right" class="q-pa-md q-gutter-sm">
          <q-btn outline label="Cancelar" color="negative" no-caps @click="onDialogCancel" />
          <q-btn color="primary" label="Salvar" type="submit" no-caps unelevated :loading="loading" />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { useDialogPluginComponent } from "quasar";
import { createFranchiseeReceivable } from "src/api/franchisee_account_receive";
import { getFinancialPlanAccountsForSelect } from "src/api/financial_plan_account";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

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

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

const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();
const today = new Date();
const dueDateIso = [
  today.getFullYear(),
  String(today.getMonth() + 1).padStart(2, "0"),
  String(today.getDate()).padStart(2, "0"),
].join("-");

const accountTypeOptions = [
  { label: "Conta interna", value: "internal" },
  { label: "Relacionada a uma unidade", value: "unit" },
];

const formRef = ref(null);
const form = ref({
  account_type: "internal",
  unit: null,
  history: "",
  value: 0,
  due_date: today.toLocaleDateString("pt-BR"),
  due_date_iso: dueDateIso,
  financial_plan_account_id: null,
  obs: "",
});
const planAccountOptions = ref([]);
const loadingPlanAccounts = ref(false);

watch(
  () => form.value.account_type,
  (type) => {
    if (type === "internal") form.value.unit = null;
  },
);

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

onMounted(async () => {
  loadingPlanAccounts.value = true;
  try {
    const accounts = await getFinancialPlanAccountsForSelect();
    planAccountOptions.value = (accounts ?? []).map((account) => ({
      label: `${account.code} — ${account.description}`,
      value: account.id,
    }));
  } finally {
    loadingPlanAccounts.value = false;
  }
});

const onSubmit = async () => {
  await submitForm(() =>
    createFranchiseeReceivable({
      account_type: form.value.account_type,
      unit_id: form.value.account_type === "unit" ? form.value.unit?.value : null,
      history: form.value.history,
      value: form.value.value,
      due_date: form.value.due_date_iso,
      financial_plan_account_id: form.value.financial_plan_account_id || null,
      obs: form.value.obs || null,
    }),
  );
};
</script>
