<template>
  <client-template>
    <template #client-new-action>
      <add-button text="Ajouter" @click="goToClient" />
    </template>
    <template #select-filter>
      <filter-table />
    </template>
    <template #client-other-action>
      <table-action />
    </template>
    <template #client-table>
      <client-table
        :data="clientData"
        :loading="loadingData"
        :pagination="pagination"
        @view="goToDetails"
        @delete="deleteClient"
        @page-change="onPageChange"
        @per-page-change="onPerPageChange"
        @search-change="onSearch"
      />
    </template>
  </client-template>
</template>
<script setup>
import ClientTemplate from "@/components/templates/CRM/ClientTemplate.vue";
import ClientTable from "@/components/molecules/Tables/CRM/ClientTable.vue";
import addButton from "@/components/molecules/new-button/addButton.vue";
import FilterTable from "@/components/molecules/Tables/FilterTable.vue";
import TableAction from "@/components/molecules/Tables/TableAction.vue";
import { defineProps, defineEmits } from "vue";
import { useRouter } from "vue-router";
import { useClientStore } from "@/stores/clientStore";
import { storeToRefs } from "pinia";

const router = useRouter();
const clientStore = useClientStore();
// Use storeToRefs to keep reactivity for pagination if it was passed as a prop, 
// but since we are using the store directly for actions, we can also extract it here if needed.
// However, the common pattern is that the parent view passes the data.
// Let's check where clientData comes from. It comes from props.

const emit = defineEmits(["pushDetails"]);

const props = defineProps({
  clientData: {
    type: Array,
    default: [],
  },
  loadingData: {
    type: Boolean,
    default: false,
  },
  // We need to accept pagination as a prop if it is passed from the view
  pagination: {
      type: Object,
      default: () => ({})
  }
});

const goToClient = () => {
  router.push({
    name: "Creation client",
  });
};

const goToDetails = (client) => {
  emit("pushDetails", client);
};

const deleteClient = (client) => {
  emit("deleteClient", client);
};

const onPageChange = (page) => {
    clientStore.fetchClients({ page: page, per_page: props.pagination.per_page });
};

const onPerPageChange = (perPage) => {
    clientStore.fetchClients({ page: 1, per_page: perPage });
};

const onSearch = (query) => {
    clientStore.fetchClients({ page: 1, per_page: props.pagination.per_page, search: query });
};
</script>
