/**
 * Hook pour récupérer les statistiques du dashboard clients - COOP-CA AMIFOND
 */

import { useQuery } from "@tanstack/react-query";

import { ClientService } from "@/services/clients.service";
import type { ExtendedClientStats } from "@/types/clients";

import { CLIENTS_QUERY_KEYS } from "./use-clients-queries";

/**
 * Hook pour récupérer les statistiques du dashboard
 */
export const useClientDashboardStats = () => {
  return useQuery({
    queryKey: [...CLIENTS_QUERY_KEYS.stats(), "dashboard"],
    queryFn: (): Promise<ExtendedClientStats> => ClientService.getClientStats() as Promise<ExtendedClientStats>,
    staleTime: 5 * 60 * 1000, // 5 minutes
    select: (data: ExtendedClientStats) => {
      // Transformer les données pour le dashboard
      return {
        totalClients: data.total_clients,
        activeClients: data.active_clients,
        newClientsThisMonth: data.new_clients_this_month,
        pendingClients: data.pending_clients ?? 0,
        monthlyGrowthRate: data.monthly_growth_rate ?? 0,
        activationRate: data.activation_rate ?? 0,
        averageAccountBalance: data.average_account_balance ?? 0,
        topBranch: data.top_branch ?? "N/A",
        clientsByType: {
          particuliers: data.individual_clients ?? 0,
          entreprises: data.business_clients ?? 0,
        },
        monthlyEvolution: data.monthly_evolution ?? [],
        chartData: {
          totalClients: data.chart_data?.total_clients ?? [],
          newClients: data.chart_data?.new_clients ?? [],
          activeClients: data.chart_data?.active_clients ?? [],
        },
      };
    },
  });
};

/**
 * Hook pour récupérer les clients récents
 */
export const useRecentClients = (limit: number = 10) => {
  return useQuery({
    queryKey: [...CLIENTS_QUERY_KEYS.lists(), "recent", limit],
    queryFn: () =>
      ClientService.getClients({
        page: 1,
        page_size: limit,
        ordering: "-date_created",
      }),
    staleTime: 2 * 60 * 1000, // 2 minutes
    select: (data) => data.results || [],
  });
};

/**
 * Hook pour récupérer les données de graphique d'évolution
 */
export const useClientEvolutionData = (months: number = 6) => {
  return useQuery({
    queryKey: [...CLIENTS_QUERY_KEYS.stats(), "evolution", months],
    queryFn: () => ClientService.getClientEvolution(months),
    staleTime: 10 * 60 * 1000, // 10 minutes
  });
};
