import { useState, useMemo, useEffect } from 'react';
import { financeiroService } from '@/services/financeiroService';

/**
 * Hook para gerenciar a lógica de Contas a Pagar com segurança.
 */
export const useContasPagar = () => {
    const [transactions, setTransactions] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [activeTab, setActiveTab] = useState('registros');
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedIds, setSelectedIds] = useState([]);

    // Carregamento de dados com tratamento de erro
    useEffect(() => {
        const loadData = async () => {
            setIsLoading(true);
            try {
                const data = await financeiroService.fetchPayables();
                if (Array.isArray(data)) {
                    setTransactions(data);
                } else {
                    console.warn("Service fetchPayables não retornou um array:", data);
                    setTransactions([]);
                }
            } catch (error) {
                console.error("Erro crítico ao carregar contas a pagar:", error);
                setTransactions([]);
            } finally {
                setIsLoading(false);
            }
        };
        loadData();
    }, []);

    // Filtros seguros
    const filteredData = useMemo(() => {
        if (!Array.isArray(transactions)) return [];
        
        return transactions.filter(item => {
            const label = (item?.favorecido || "").toLowerCase();
            const id = (item?.id || "").toLowerCase();
            const search = (searchTerm || "").toLowerCase();
            
            return label.includes(search) || id.includes(search);
        });
    }, [transactions, searchTerm]);

    // KPIs seguros
    const kpis = useMemo(() => {
        if (!Array.isArray(transactions)) return { totalPago: 0, totalPendente: 0, totalAtrasado: 0, totalGeral: 0 };

        const pago = transactions.filter(i => i?.status === 'PAGO').reduce((acc, curr) => acc + (curr?.valor || 0), 0);
        const pendente = transactions.filter(i => i?.status === 'PENDENTE').reduce((acc, curr) => acc + (curr?.valor || 0), 0);
        const atrasado = transactions.filter(i => i?.status === 'ATRASADO').reduce((acc, curr) => acc + (curr?.valor || 0), 0);
        
        return {
            totalPago: pago,
            totalPendente: pendente,
            totalAtrasado: atrasado,
            totalGeral: pago + pendente + atrasado
        };
    }, [transactions]);

    // Ações
    const toggleSelect = (id) => {
        setSelectedIds(prev => 
            prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
        );
    };

    const toggleSelectAll = () => {
        if (selectedIds.length === filteredData.length) {
            setSelectedIds([]);
        } else {
            setSelectedIds(filteredData.map(d => d.id));
        }
    };

    const deleteTransaction = async (id) => {
        try {
            await financeiroService.deleteTransaction(id);
            setTransactions(prev => prev.filter(t => t.id !== id));
            setSelectedIds(prev => prev.filter(i => i !== id));
        } catch (error) {
            console.error("Erro ao deletar transação:", error);
        }
    };

    const markAsPaid = async (id) => {
        try {
            await financeiroService.markAsPaid(id);
            setTransactions(prev => prev.map(t => 
                t.id === id ? { ...t, status: 'PAGO' } : t
            ));
        } catch (error) {
            console.error("Erro ao marcar como pago:", error);
        }
    };

    return {
        state: {
            activeTab,
            transactions: filteredData,
            kpis,
            searchTerm,
            selectedIds,
            totalCount: transactions.length,
            isLoading
        },
        actions: {
            setActiveTab,
            setSearchTerm,
            toggleSelect,
            toggleSelectAll,
            deleteTransaction,
            markAsPaid
        }
    };
};
