<template>
  <client-detail-presentation
    v-if="clientStore.currentClient"
    :client="clientStore.currentClient"
    :contacts="contacts_client"
    :is-loading="clientStore.isLoading"
    :client-avatar="clientAvatar"
    :active-tab="activeTab"
    :file-input="fileInput"
    :contact-loading="contactStore.isLoading"
    @update-the-client="updateClient"
    @add-new-contact="createNewContact"
  />
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { useClientStore } from "@/stores/clientStore";
import { useContactStore } from "@/stores/contactStore";
import ClientDetailPresentation from "@/components/Organism/CRM/ClientDetailPresentation.vue";
const route = useRoute();
const clientStore = useClientStore();
const contactStore = useContactStore();

// Ensure client_id is a number
const client_id = Number(route.params.id);
const contacts_client = ref([]);
const activeTab = ref("overview");
const clientAvatar = ref(null);
const fileInput = ref(null);

onMounted(async () => {
  if (client_id) {
    await clientStore.fetchClient(client_id);
    contacts_client.value = await contactStore.getClientListContact(client_id);
  }
});

const updateClient = async (data) => {
  if (!client_id) {
    console.error("Missing client id");
    return;
  }

  // If data is FormData (e.g. file upload), append the id instead of spreading
  if (data instanceof FormData) {
    data.set("id", String(client_id));
    await clientStore.updateClient(data);
  } else {
    await clientStore.updateClient({ id: client_id, ...data });
  }
};

const createNewContact = async (data) => {
  try {
    await contactStore.createContact(data);
    // Refresh contacts list after creation
    contacts_client.value = await contactStore.getClientListContact(client_id);
  } catch (error) {
    console.error("Error creating contact:", error);
  }
};
</script>
