<template>
  <div class="container-fluid py-4">
    <div class="d-sm-flex justify-content-between mb-4">
      <div>
        <h5 class="mb-0">Entrepôts</h5>
        <p class="text-sm mb-0">Gestion des lieux de stockage et dépôts.</p>
      </div>
      <div class="mt-sm-0 mt-3">
        <soft-button color="info" variant="gradient" @click="handleCreate">
          <i class="fas fa-plus me-2"></i> Nouvel Entrepôt
        </soft-button>
      </div>
    </div>
    <div class="row">
      <div class="col-12">
        <warehouse-table
          :data="warehouses"
          :loading="loading"
          @view="handleView"
          @edit="handleEdit"
          @delete="handleDelete"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted } from "vue";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import WarehouseTable from "@/components/molecules/Tables/Stock/WarehouseTable.vue";
import SoftButton from "@/components/SoftButton.vue";
import { useWarehouseStore } from "@/stores/warehouseStore";

const router = useRouter();
const warehouseStore = useWarehouseStore();
const { warehouses, loading } = storeToRefs(warehouseStore);

const handleCreate = () => {
  router.push("/stock/warehouses/new");
};

const handleView = (id) => {
  router.push(`/stock/warehouses/${id}`);
};

const handleEdit = (id) => {
  router.push(`/stock/warehouses/${id}/edit`);
};

const handleDelete = async (id) => {
  if (confirm("Êtes-vous sûr de vouloir supprimer cet entrepôt ?")) {
    try {
      await warehouseStore.deleteWarehouse(id);
    } catch (error) {
      console.error("Failed to delete warehouse", error);
    }
  }
};

onMounted(() => {
  warehouseStore.fetchWarehouses();
});
</script>
