<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"
      />

      <DefaultForm ref="formRef" @submit.prevent="onSubmit">
        <q-scroll-area ref="scrollAreaRef" class="form-dialog-scroll-area">
          <q-card-section class="row q-col-gutter-md q-pt-none">
            <DefaultInput
              v-model="form.history"
              v-model:error="validationErrors.history"
              class="col-12"
              label="Descrição"
              :error-message="validationErrors.history"
              :rules="[inputRules.required, inputRules.max(255)]"
            />

            <div class="col-12">
              <div class="text-caption text-grey-8 q-mb-xs">
                Tipo da conta <span class="text-negative">*</span>
              </div>

              <q-option-group
                v-model="form.account_type"
                color="primary"
                inline
                type="radio"
                :options="accountTypeOptions"
              />
            </div>

            <UnitSelect
              v-if="form.account_type === 'unit'"
              v-model="form.unit"
              v-model:error="validationErrors.unit_id"
              class="col-12"
              label="Unidade"
              :error-message="validationErrors.unit_id"
              :rules="[inputRules.required]"
            />

            <DefaultCurrencyInput
              v-model="form.value"
              v-model:error="validationErrors.value"
              class="col-12 col-sm-6"
              label="Valor"
              :error-message="validationErrors.value"
              :rules="[inputRules.requiredNumber, inputRules.minValue(0.01)]"
            />

            <DefaultInputDatePicker
              v-model="form.due_date"
              v-model:untreated-date="form.due_date_iso"
              v-model:error="validationErrors.due_date"
              class="col-12 col-sm-6"
              label="Data de vencimento"
              :error-message="validationErrors.due_date"
              :rules="[inputRules.required]"
            />

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

            <DefaultInput
              v-model="form.obs"
              v-model:error="validationErrors.obs"
              class="col-12"
              label="Observação"
              rows="3"
              type="textarea"
              :error-message="validationErrors.obs"
              :rules="[inputRules.max(1000)]"
            />
          </q-card-section>
        </q-scroll-area>

        <q-separator />
        <q-card-actions align="right" class="q-pa-md q-gutter-sm">
          <q-btn
            color="negative"
            label="Cancelar"
            no-caps
            outline
            @click="onDialogCancel"
          />

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

<script setup>
import { createFranchiseeReceivable } from "src/api/franchisee_account_receive";
import { getFinancialPlanAccountsForSelect } from "src/api/financial_plan_account";
import { onMounted, ref, watch } from "vue";
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 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 scrollAreaRef = ref(null);
const { inputRules } = useInputRules();
const { scrollToComponent } = useScroll();

const { form } = useForm(
  {
    account_type: "internal",
    unit: null,
    history: "",
    value: 0,
    due_date: today.toLocaleDateString("pt-BR"),
    due_date_iso: dueDateIso,
    financial_plan_account_id: null,
    obs: "",
  },
  { containerRef: scrollAreaRef },
);

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

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

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

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

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;
  }
});
</script>
