<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <div style="width: 100%; max-width: 600px">
      <q-card class="overflow-hidden" style="width: 100%">
        <DefaultDialogHeader
          :title="isEdit ? 'Editar Produto' : 'Novo Produto'"
          @close="onDialogCancel"
        />

        <q-form ref="formRef" @submit="onOKClick">
          <q-card-section class="q-pt-sm">
            <div class="text-h6 q-mb-sm">Produto</div>

            <div class="row q-col-gutter-sm">
              <DefaultInput
                v-model="form.name"
                label="Nome do Produto"
                class="col-12"
              />

              <DefaultInput
                v-model="form.description"
                label="Descrição"
                class="col-12"
                type="textarea"
                autogrow
              />

              <DefaultCurrencyInput
                v-model="form.unitPrice"
                label="Valor Unitário"
                class="col-4"
              />

              <DefaultInput
                v-model="form.quantity"
                label="Quantidade"
                class="col-4"
                type="number"
                min="0"
              />

              <DefaultInput
                :model-value="totalValueFormatted"
                label="Valor Total do Produto"
                class="col-4"
                disable
                readonly
              />
            </div>
          </q-card-section>

          <q-card-actions align="right" class="q-px-md q-pb-md">
            <q-btn
              label="Cancelar"
              outline
              color="primary-2"
              @click="onDialogCancel"
            />
            <q-btn
              :label="isEdit ? 'Salvar Alterações' : 'Cadastrar Produto'"
              color="primary-2"
              type="submit"
              :loading="loading"
            />
          </q-card-actions>
        </q-form>
      </q-card>
    </div>
  </q-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import { useDialogPluginComponent, useQuasar } from "quasar";
import { createProduct, updateProduct } from "src/api/product";
import { formatToBRLCurrency } from "src/helpers/utils";

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

const props = defineProps({
  product: {
    type: Object,
    default: null,
  },
});

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

const $q = useQuasar();

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

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

const isEdit = computed(() => !!props.product);

const form = ref({
  name:        props.product?.name        ?? "",
  description: props.product?.description ?? "",
  unitPrice:   props.product?.price_sale  ?? 0,
  quantity:    props.product?.quantity    ?? 0,
});

const totalValue = computed(() => form.value.unitPrice * form.value.quantity);
const totalValueFormatted = computed(() => formatToBRLCurrency(totalValue.value));

const onOKClick = async () => {
  loading.value = true;
  try {
    const payload = {
      name:        form.value.name,
      description: form.value.description,
      price_sale:  form.value.unitPrice,
      quantity:    Number(form.value.quantity),
    };
    const product = isEdit.value
      ? await updateProduct(props.product.id, payload)
      : await createProduct(payload);
    onDialogOK(product);
  } catch {
    $q.notify({
      type: "negative",
      message: isEdit.value ? "Erro ao editar produto." : "Erro ao cadastrar produto.",
    });
  } finally {
    loading.value = false;
  }
};
</script>
