<template>
  <div class="container-fluid py-4">
    <div class="row">
      <div class="col-lg-8 mx-auto">
        <div class="card">
          <div class="card-header pb-0 p-3">
            <div class="d-flex justify-content-between align-items-center">
              <h6 class="mb-0">Nouvelle Réception de Marchandise</h6>
              <soft-button
                color="secondary"
                variant="outline"
                size="sm"
                @click="goBack"
              >
                <i class="fas fa-arrow-left me-2"></i>Retour
              </soft-button>
            </div>
          </div>
          <div class="card-body p-3">
            <new-reception-form
              :loading="loading"
              :purchase-orders="purchaseOrders"
              @submit="handleSubmit"
              @cancel="goBack"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import NewReceptionForm from "@/components/molecules/Stock/NewReceptionForm.vue";
import SoftButton from "@/components/SoftButton.vue";
import { useGoodsReceiptStore } from "@/stores/goodsReceiptStore";
import { usePurchaseOrderStore } from "@/stores/purchaseOrderStore";

const router = useRouter();
const goodsReceiptStore = useGoodsReceiptStore();
const purchaseOrderStore = usePurchaseOrderStore();

const { loading } = storeToRefs(goodsReceiptStore);

const purchaseOrders = ref([]);

const goBack = () => {
  router.back();
};

const handleSubmit = async (formData) => {
  try {
    await goodsReceiptStore.createGoodsReceipt(formData);
    router.push("/stock/receptions");
  } catch (error) {
    console.error("Failed to create goods receipt", error);
  }
};

onMounted(async () => {
  try {
    await purchaseOrderStore.fetchPurchaseOrders();
    purchaseOrders.value = purchaseOrderStore.purchaseOrders;
  } catch (error) {
    console.error("Failed to load purchase orders", error);
  }
});
</script>
