<template>
  <thanatopractitioner-presentation
    :thanatopractitioner-data="thanatopractitionerStore.thanatopractitioners"
    :loading-data="thanatopractitionerStore.loading"
    :pagination="thanatopractitionerStore.getPagination"
    @push-details="goDetails"
    @delete-thanatopractitioner="confirmDeleteThanatopractitioner"
    @change-page="changePage"
  />

  <!-- Confirm Delete Modal -->
  <confirm-modal
    :is-visible="confirmModal.isVisible"
    :title="confirmModal.title"
    :message="confirmModal.message"
    :details="confirmModal.details"
    :type="confirmModal.type"
    :confirm-text="confirmModal.confirmText"
    :cancel-text="confirmModal.cancelText"
    :is-loading="confirmModal.isLoading"
    @confirm="handleConfirmDelete"
    @cancel="handleCancelDelete"
    @close="handleCancelDelete"
  />
</template>

<script setup>
import { reactive, onMounted } from "vue";
import ThanatopractitionerPresentation from "@/components/Organism/Thanatopractitioner/ThanatopractitionerPresentation.vue";
import ConfirmModal from "@/components/molecules/common/ConfirmModal.vue";
import { useThanatopractitionerStore } from "@/stores/thanatopractitionerStore";
import { useNotificationStore } from "@/stores/notification";
import { useRouter } from "vue-router";

const thanatopractitionerStore = useThanatopractitionerStore();
const notificationStore = useNotificationStore();
const router = useRouter();

// Confirm modal state
const confirmModal = reactive({
  isVisible: false,
  title: "Supprimer le thanatopractitioner",
  message: "",
  details:
    "Cette action est irréversible. Toutes les données associées seront définitivement supprimées.",
  type: "danger",
  confirmText: "Supprimer",
  cancelText: "Annuler",
  isLoading: false,
  thanatopractitionerId: null,
  thanatopractitionerName: "",
});

onMounted(async () => {
  await thanatopractitionerStore.fetchThanatopractitioners();
});

const goDetails = (id) => {
  router.push({
    name: "Thanatopractitioner details",
    params: {
      id: id,
    },
  });
};

const confirmDeleteThanatopractitioner = (thanatopractitionerId) => {
  console.log(
    "confirmDeleteThanatopractitioner called with ID:",
    thanatopractitionerId
  );
  console.log("Thanatopractitioner ID type:", typeof thanatopractitionerId);
  console.log(
    "Store thanatopractitioners:",
    thanatopractitionerStore.thanatopractitioners
  );
  console.log(
    "Store thanatopractitioners length:",
    thanatopractitionerStore.thanatopractitioners.length
  );

  const thanatopractitioner = thanatopractitionerStore.thanatopractitioners.find(
    (prac) => prac.id === thanatopractitionerId
  );
  console.log("Found thanatopractitioner:", thanatopractitioner);

  if (thanatopractitioner) {
    console.log("Showing confirmation modal");
    confirmModal.isVisible = true;
    confirmModal.thanatopractitionerId = thanatopractitionerId;
    confirmModal.thanatopractitionerName = `${thanatopractitioner.first_name} ${thanatopractitioner.last_name}`;
    confirmModal.message = `Êtes-vous sûr de vouloir supprimer le thanatopractitioner "${confirmModal.thanatopractitionerName}" ?`;
  } else {
    console.log("No thanatopractitioner found - trying to parse as number");
    const numericId = parseInt(thanatopractitionerId, 10);
    console.log("Trying with numeric ID:", numericId);
    const thanatopractitionerByNumber = thanatopractitionerStore.thanatopractitioners.find(
      (prac) => prac.id === numericId
    );
    console.log("Found by numeric ID:", thanatopractitionerByNumber);

    if (thanatopractitionerByNumber) {
      console.log("Showing confirmation modal with numeric ID");
      confirmModal.isVisible = true;
      confirmModal.thanatopractitionerId = numericId;
      confirmModal.thanatopractitionerName = `${thanatopractitionerByNumber.first_name} ${thanatopractitionerByNumber.last_name}`;
      confirmModal.message = `Êtes-vous sûr de vouloir supprimer le thanatopractitioner "${confirmModal.thanatopractitionerName}" ?`;
    } else {
      console.log(
        "Still no thanatopractitioner found - displaying all thanatopractitioner IDs for comparison"
      );
      thanatopractitionerStore.thanatopractitioners.forEach((prac, index) => {
        console.log(
          `Thanatopractitioner ${index}: ID=${
            prac.id
          } (${typeof prac.id}), Name=${prac.first_name} ${prac.last_name}`
        );
      });
    }
  }
};

const handleConfirmDelete = async () => {
  const thanatopractitionerId = confirmModal.thanatopractitionerId;
  const thanatopractitionerName = confirmModal.thanatopractitionerName;
  console.log("Test");
  try {
    confirmModal.isLoading = true;
    await thanatopractitionerStore.deleteThanatopractitioner(
      thanatopractitionerId
    );
    notificationStore.success(
      "Thanatopractitioner supprimé",
      `Le thanatopractitioner ${thanatopractitionerName} a été supprimé avec succès.`
    );
    closeConfirmModal();
  } catch (error) {
    console.error("Error deleting thanatopractitioner:", error);
    notificationStore.error(
      "Erreur de suppression",
      "Une erreur est survenue lors de la suppression du thanatopractitioner."
    );
    closeConfirmModal();
  }
};

const handleCancelDelete = () => {
  closeConfirmModal();
};

const closeConfirmModal = () => {
  confirmModal.isVisible = false;
  confirmModal.thanatopractitionerId = null;
  confirmModal.thanatopractitionerName = "";
  confirmModal.isLoading = false;
};

const changePage = async (page) => {
  console.log("changePage called in Thanatopractitioners.vue with page:", page);
  try {
    console.log("Fetching thanatopractitioners with page:", page);
    await thanatopractitionerStore.fetchThanatopractitioners({
      page,
      per_page: 10,
    });
  } catch (error) {
    console.error("Error changing page:", error);
    notificationStore.error(
      "Erreur de pagination",
      "Une erreur est survenue lors du changement de page."
    );
  }
};
</script>
