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

export function useStatementRefData() {
  const [categories, setCategories] = useState([]);
  const [rules, setRules] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        setLoading(true);
        const [catResponse, rulesResponse] = await Promise.all([
          conciliacaoService.fetchCategories(),
          conciliacaoService.fetchRules()
        ]);

        // Normalize categories
        const catRaw = catResponse?.data ?? catResponse;
        const catList = Array.isArray(catRaw) 
          ? catRaw 
          : (catRaw?.dados ?? catRaw?.Base_Dados_API ?? Object.values(catRaw || {}));
        
        // Normalize rules
        const rulesRaw = rulesResponse?.data ?? rulesResponse;
        const rulesList = Array.isArray(rulesRaw) 
          ? rulesRaw 
          : (rulesRaw?.dados ?? rulesRaw?.Base_Dados_API ?? Object.values(rulesRaw || {}));

        setCategories(Array.isArray(catList) ? catList : []);
        setRules(Array.isArray(rulesList) ? rulesList : []);
      } catch (err) {
        console.error('[useStatementRefData] Error fetching ref data:', err);
        setError(err);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, []);

  function getCategoryName(id) {
    if (!id) return null;
    const cat = categories.find(c => String(c.idcategoria) === String(id));
    return cat?.categoria || cat?.nome || 'Não categorizado';
  }

  function getRuleName(id) {
    if (!id) return null;
    const rule = rules.find(r => String(r.id) === String(id) || String(r.idregras_financeiro) === String(id));
    return rule?.regra || rule?.nome || null;
  }

  return {
    categories,
    rules,
    loading,
    error,
    getCategoryName,
    getRuleName
  };
}
