<template>
  <add-thanatopractitioner-presentation
    :employees="employeeStore.employees"
    :loading="thanatopractitionerStore.isLoading"
    :validation-errors="validationErrors"
    :success="showSuccess"
    @create-thanatopractitioner="handleCreateThanatopractitioner"
  />
</template>

<script setup>
import AddThanatopractitionerPresentation from "@/components/Organism/Thanatopractitioner/AddThanatopractitionerPresentation.vue";
import { useThanatopractitionerStore } from "@/stores/thanatopractitionerStore";
import { useEmployeeStore } from "@/stores/employeeStore";
import { useNotificationStore } from "@/stores/notification";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const thanatopractitionerStore = useThanatopractitionerStore();
const employeeStore = useEmployeeStore();
const notificationStore = useNotificationStore();
const validationErrors = ref({});
const showSuccess = ref(false);

onMounted(async () => {
  // Fetch active employees for selection
  await employeeStore.fetchEmployees();
});

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

    // Call the store to create thanatopractitioner
    const thanatopractitioner = await thanatopractitionerStore.createThanatopractitioner(
      form
    );

    // Show success notification
    notificationStore.created("Thanatopractitioner");
    showSuccess.value = true;

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

    // Handle validation errors from Laravel
    if (error.response && error.response.status === 422) {
      validationErrors.value = error.response.data.errors || {};
      notificationStore.error(
        "Erreur de validation",
        "Veuillez corriger les erreurs dans le formulaire"
      );
    } else if (error.response && error.response.data) {
      // Handle other API errors
      const errorMessage =
        error.response.data.message || "Une erreur est survenue";
      notificationStore.error("Erreur", errorMessage);
    } else {
      notificationStore.error("Erreur", "Une erreur inattendue s'est produite");
    }
  }
};
</script>
