<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">Créer un nouvel avoir</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-avoir-form @submit="handleSubmit" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from "vue-router";
import NewAvoirForm from "@/components/molecules/Avoir/NewAvoirForm.vue";
import SoftButton from "@/components/SoftButton.vue";
import { useAvoirStore } from "@/stores/avoirStore";
import { useNotificationStore } from "@/stores/notification";

const router = useRouter();
const avoirStore = useAvoirStore();
const notificationStore = useNotificationStore();

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

const handleSubmit = async (formData) => {
  try {
    const payload = {
      client_id: formData.clientId,
      invoice_id: formData.invoiceId,
      avoir_number: formData.number,
      status: formData.status,
      avoir_date: formData.date,
      reason_type: formData.reason,
      reason_description: formData.reasonDetail,
      lines: formData.lines.map((line) => ({
        description: line.designation,
        quantity: line.quantity,
        unit_price: line.priceHt,
        tva_rate: 0,
      })),
    };

    await avoirStore.createAvoir(payload);
    notificationStore.success(
      "Succès",
      `Avoir créé avec succès: ${formData.number}`
    );
    router.push("/avoirs");
  } catch (err) {
    console.error("Error creating avoir:", err);
    notificationStore.error("Erreur", "Erreur lors de la création de l'avoir");
  }
};
</script>
