<template>
  <div class="column" style="gap: 8px">
    <div v-if="loading" class="row justify-center q-pa-lg">
      <q-spinner color="primary" size="32px" />
    </div>

    <template v-else>
      <ProductCard
        v-for="product in products"
        :key="product.id"
        :title="product.name"
        :description="product.description"
        :unit-price="product.price_sale"
        :current-stock="product.quantity"
        :total-value="product.price_sale * product.quantity"
        :can-edit="canEdit"
        :can-delete="canDelete"
        @edit="handleEdit(product)"
        @delete="handleDelete(product)"
      />

      <div v-if="products.length === 0" class="text-center text-grey q-pa-lg">
        Nenhum produto cadastrado.
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import ProductCard from "../components/ProductCard.vue";
import AddEditProductDialog from "../components/AddEditProductDialog.vue";
import { getProducts, deleteProduct } from "src/api/product";
import { permissionStore } from "src/stores/permission";

const $q = useQuasar();
const permissions = permissionStore();
const canEdit = permissions.getAccess("franchisor_products", "edit");
const canDelete = permissions.getAccess("franchisor_products", "delete");

const products = ref([]);
const loading = ref(false);

const fetchProducts = async () => {
  loading.value = true;
  try {
    products.value = await getProducts();
  } catch {
    $q.notify({ type: "negative", message: "Erro ao carregar produtos." });
  } finally {
    loading.value = false;
  }
};

onMounted(fetchProducts);

defineExpose({ fetchProducts });

const handleEdit = (product) => {
  $q.dialog({
    component: AddEditProductDialog,
    componentProps: { product },
  }).onOk((updated) => {
    const index = products.value.findIndex((p) => p.id === product.id);
    if (index !== -1) {
      products.value[index] = updated;
    }
  });
};

const handleDelete = (product) => {
  $q.dialog({
    title: "Excluir Produto",
    message: `Deseja excluir o produto "${product.name}"?`,
    cancel: { label: "Cancelar", flat: true, color: "primary" },
    ok: { label: "Excluir", color: "negative" },
    persistent: true,
  }).onOk(async () => {
    try {
      await deleteProduct(product.id);
      products.value = products.value.filter((p) => p.id !== product.id);
      $q.notify({ type: "positive", message: "Produto excluído com sucesso." });
    } catch {
      $q.notify({ type: "negative", message: "Erro ao excluir produto." });
    }
  });
};
</script>
