<template>
  <add-client-presentation
    :categories="categoryClientStore.activeCategories"
    :loading="clientStore.isLoading"
    :validation-errors="validationErrors"
    :success="showSuccess"
    @create-client="handleCreateClient"
  />
</template>
<script setup>
import AddClientPresentation from "@/components/Organism/CRM/AddClientPresentation.vue";
import { useClientCategoryStore } from "@/stores/clientCategorie.store";
import { useClientStore } from "@/stores/clientStore";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const categoryClientStore = useClientCategoryStore();
const clientStore = useClientStore();
const validationErrors = ref({});
const showSuccess = ref(false);

onMounted(async () => {
  await categoryClientStore.fetchActiveCategories();
});

const handleCreateClient = async (form) => {
  try {
    // Clear previous errors
    validationErrors.value = {};
    showSuccess.value = false;

    // Call the store to create client
    const client = await clientStore.createClient(form);

    // Show success message
    showSuccess.value = true;

    // Redirect after 2 seconds
    setTimeout(() => {
      router.push({ name: "Clients" });
    }, 2000);
  } catch (error) {
    console.error("Error creating client:", error);

    // Handle validation errors from Laravel
    if (error.response && error.response.status === 422) {
      validationErrors.value = error.response.data.errors || {};
    } else if (error.response && error.response.data) {
      // Handle other API errors
      const errorMessage =
        error.response.data.message || "Une erreur est survenue";
      alert(errorMessage);
    } else {
      alert("Une erreur inattendue s'est produite");
    }
  }
};
</script>
