import { useState } from 'react';
import { getClienteDetalle, refreshClientes, searchClientesOptimizacion } from '../../../../services/dataService';
import { DashboardCliente } from '../types';

export function useClienteDashboardData() {
    const [clientes, setClientes] = useState<DashboardCliente[]>([]);
    const [selectedCliente, setSelectedCliente] = useState<DashboardCliente | null>(null);
    const [loading, setLoading] = useState(false);

    const handleSearch = async (term: string) => {
        if (!term) {
            setClientes([]);
            return;
        }

        try {
            setLoading(true);
            const response = await searchClientesOptimizacion(term);
            setClientes((response?.data ?? []) as DashboardCliente[]);
        } finally {
            setLoading(false);
        }
    };

    const refreshSelectedCliente = async (codCli?: number) => {
        const id = codCli ?? selectedCliente?.CodCli;
        if (!id) return;

        await refreshClientes().catch(() => null);
        const detalle = await getClienteDetalle(id, true);
        if (detalle?.data) {
            setSelectedCliente(detalle.data as DashboardCliente);
        }
    };


    return {
        clientes,
        selectedCliente,
        loading,
        setSelectedCliente,
        handleSearch,
        refreshSelectedCliente,
    };
}
