<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <div style="width: 100%; max-width: 680px">
      <q-card class="overflow-hidden" style="width: 100%">
        <DefaultDialogHeader title="Importar Pedido" @close="onDialogCancel" />

        <q-card-section class="q-pt-sm">
          <div class="row items-center q-col-gutter-sm">
            <div class="col">
              <q-file
                v-model="selectedFile"
                outlined
                dense
                accept=".xlsx,.xls"
                label="Pesquisar arquivo Excel..."
                @update:model-value="importedRows = []"
              >
                <template #prepend>
                  <q-icon name="mdi-file-excel-outline" color="secondary" />
                </template>
              </q-file>
            </div>

            <div class="col-auto">
              <q-btn
                label="Importar"
                color="primary-2"
                :loading="loading"
                :disable="!selectedFile"
                style="height: 40px"
                @click="handleImport"
              />
            </div>
          </div>

          <template v-if="importedRows.length > 0">
            <q-separator class="q-my-md" />

            <q-table
              flat
              dense
              :rows="importedRows"
              :columns="columns"
              row-key="name"
              hide-bottom
              :pagination="{ rowsPerPage: 0 }"
            >
              <template #body-cell-price_sale="{ row }">
                <q-td>{{ formatToBRLCurrency(row.price_sale) }}</q-td>
              </template>
              <template #body-cell-subtotal="{ row }">
                <q-td>{{ formatToBRLCurrency(row.price_sale * row.quantity) }}</q-td>
              </template>
            </q-table>

            <div class="row justify-end q-mt-sm q-pr-sm">
              <span class="text-body2">
                Total:
                <strong>{{ formatToBRLCurrency(total) }}</strong>
              </span>
            </div>
          </template>
        </q-card-section>

        <q-card-actions align="right" class="q-px-md q-pb-md">
          <q-btn
            label="Fechar"
            outline
            color="primary-2"
            @click="importedRows.length > 0 ? onDialogOK() : onDialogCancel()"
          />
        </q-card-actions>
      </q-card>
    </div>
  </q-dialog>
</template>

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

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

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

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

const selectedFile = ref(null);
const loading = ref(false);
const importedRows = ref([]);

const columns = [
  { name: "name",      label: "Descrição", field: "name",      align: "left" },
  { name: "quantity",  label: "Qtde",      field: "quantity",  align: "center" },
  { name: "price_sale", label: "Preço",   field: "price_sale", align: "right" },
  { name: "subtotal",  label: "Subtotal",  field: "subtotal",  align: "right" },
];

const total = computed(() =>
  importedRows.value.reduce((sum, r) => sum + r.price_sale * r.quantity, 0)
);

const handleImport = async () => {
  if (!selectedFile.value) return;

  loading.value = true;
  try {
    importedRows.value = await importProducts(selectedFile.value);
  } catch (err) {
    const msg = err?.response?.data?.message ?? "Erro ao importar arquivo.";
    $q.notify({ type: "negative", message: msg });
  } finally {
    loading.value = false;
  }
};
</script>
