<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden treasury-dialog-card">
      <DefaultDialogHeader :title="launch ? 'Editar movimentação' : 'Nova movimentação'" @close="onDialogCancel" />

      <q-form ref="formRef" @submit="onOKClick">
        <q-card-section class="row q-col-gutter-md q-px-lg q-pt-md q-pb-sm">
          <DefaultSelect
            v-model="form.transaction_type"
            label="Tipo"
            :options="transactionTypeOptions"
            class="col-12"
            outlined
            emit-value
            map-options
          />
          <DefaultInput
            v-model="form.description"
            label="Descrição"
            class="col-12"
            outlined
            :rules="[(v) => !!v || 'Informe a descrição']"
          />
          <DefaultCurrencyInput
            v-model="form.amount"
            label="Valor"
            class="col-12 col-sm-6"
            outlined
          />
          <DefaultInputDatePicker
            v-model="form.launch_date"
            v-model:untreated-date="form.launch_date_iso"
            label="Data"
            class="col-12 col-sm-6"
          />
        </q-card-section>

        <q-card-actions align="right" class="q-px-lg q-pt-md q-pb-lg q-gutter-sm">
          <q-btn flat label="Cancelar" color="grey-7" @click="onDialogCancel" />
          <q-btn color="primary-2" label="Salvar" type="submit" :loading="loading" />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref } from "vue";
import { useDialogPluginComponent } from "quasar";
import { createTreasuryLaunchMe, updateTreasuryLaunchMe } from "src/api/treasury";

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";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";

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

const props = defineProps({
  accountId: {
    type: Number,
    required: true,
  },
  launch: {
    type: Object,
    default: null,
  },
});

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

const formRef = ref(null);
const loading = ref(false);

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

const form = ref({
  transaction_type: props.launch?.transaction_type ?? "entrada",
  description: props.launch?.description ?? "",
  amount: props.launch?.amount ?? 0,
  launch_date: props.launch?.launch_date
    ? props.launch.launch_date.split("-").reverse().join("/")
    : new Date().toLocaleDateString("pt-BR"),
  launch_date_iso: props.launch?.launch_date ?? new Date().toISOString().slice(0, 10),
});

async function onOKClick() {
  const valid = await formRef.value?.validate();
  if (!valid) return;

  loading.value = true;

  try {
    const payload = {
      account_id: props.accountId,
      transaction_type: form.value.transaction_type,
      description: form.value.description,
      amount: form.value.amount,
      launch_date: form.value.launch_date_iso,
    };

    if (props.launch) await updateTreasuryLaunchMe(props.launch.id, payload);
    else await createTreasuryLaunchMe(payload);

    onDialogOK(true);
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
}
</script>

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