import { useRef, 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 [detailLoading, setDetailLoading] = useState(false);
    const [detailError, setDetailError] = useState<string | null>(null);
    const lastCodCliRef = useRef<number | null>(null);

    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 ?? lastCodCliRef.current ?? undefined;
        if (!id) return;

        lastCodCliRef.current = id;
        setDetailLoading(true);
        setDetailError(null);
        try {
            await refreshClientes().catch(() => null);
            const detalle = await getClienteDetalle(id, true);
            if (detalle?.data) {
                setSelectedCliente(detalle.data as DashboardCliente);
            }
        } catch (e: any) {
            setDetailError(e?.response?.data?.message || 'No se pudo cargar la información del cliente.');
        } finally {
            setDetailLoading(false);
        }
    };

    const retryDetalle = () => refreshSelectedCliente();

    return {
        clientes,
        selectedCliente,
        loading,
        detailLoading,
        detailError,
        setSelectedCliente,
        handleSearch,
        refreshSelectedCliente,
        retryDetalle,
    };
}
