<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden" style="width: 460px; max-width: 90vw">
      <DefaultDialogHeader title="Dar baixa" @close="onDialogCancel" />

      <q-form ref="formRef" @submit.prevent="onSubmit">
        <q-card-section class="row q-col-gutter-md q-pt-none">
          <div class="col-12 text-body2 text-grey-8">{{ payable.history }}</div>

          <DefaultInputDatePicker
            v-model="form.payment_date"
            v-model:untreated-date="form.payment_date_iso"
            label="Data do pagamento"
            class="col-12"
            lazy-rules="ondemand"
            :rules="[(value) => !!value || 'Informe a data do pagamento']"
          />

          <DefaultCurrencyInput
            v-model="form.discount"
            label="Desconto"
            class="col-12 col-sm-6"
          />
          <DefaultCurrencyInput
            v-model="form.fine"
            label="Multa/Juros"
            class="col-12 col-sm-6"
          />

          <div class="col-12 text-caption text-grey-7">
            Valor da conta: {{ formatCurrency(payable.value) }} ·
            <span class="text-weight-medium">Pago: {{ formatCurrency(netValue) }}</span>
          </div>
        </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="Confirmar baixa"
            type="submit"
            no-caps
            unelevated
            :loading="loading"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { computed, ref } from "vue";
import { useDialogPluginComponent } from "quasar";
import { settleCompanyPayable } from "src/api/company_payable";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

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

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

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

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

const today = new Date();
const paymentDateIso = [
  today.getFullYear(),
  String(today.getMonth() + 1).padStart(2, "0"),
  String(today.getDate()).padStart(2, "0"),
].join("-");

const formRef = ref(null);
const form = ref({
  payment_date: today.toLocaleDateString("pt-BR"),
  payment_date_iso: paymentDateIso,
  discount: Number(payable.discount ?? 0),
  fine: Number(payable.fine ?? 0),
});

const netValue = computed(
  () =>
    Number(payable.value ?? 0) -
    Number(form.value.discount ?? 0) +
    Number(form.value.fine ?? 0),
);

const formatCurrency = (value) =>
  new Intl.NumberFormat("pt-BR", {
    style: "currency",
    currency: "BRL",
  }).format(Number(value ?? 0));

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

const onSubmit = async () => {
  await submitForm(() =>
    settleCompanyPayable(payable.id, {
      payment_date: form.value.payment_date_iso,
      discount: form.value.discount,
      fine: form.value.fine,
    }),
  );
};
</script>
