
import { useCallback } from 'react';
import { useTransactionsState } from './useTransactionsState';
import { useTransactionsFiltering } from './useTransactionsFiltering';
import { useTransactionsLoader } from './useTransactionsLoader';
import { useTransactionsOperations } from './transactionOperations/useTransactionsOperations';
import { useTransactionsEvents } from './useTransactionsEvents';

/**
 * 핵심 트랜잭션 훅 - 성능 및 안정성 최적화 버전
 * 모든 트랜잭션 관련 훅을 통합
 */
export const useTransactionsCore = () => {
  // 상태 관리
  const { 
    transactions,
    setTransactions,
    filteredTransactions,
    setFilteredTransactions,
    selectedMonth,
    setSelectedMonth,
    searchQuery,
    setSearchQuery,
    isLoading,
    setIsLoading,
    error,
    setError,
    totalBudget,
    setTotalBudget,
    refreshKey,
    setRefreshKey
  } = useTransactionsState();

  // 데이터 로딩
  const { loadTransactions } = useTransactionsLoader(
    setTransactions, 
    setTotalBudget, 
    setIsLoading, 
    setError
  );

  // 필터링 - 성능 개선 버전
  const { 
    handlePrevMonth, 
    handleNextMonth,
    getTotalExpenses
  } = useTransactionsFiltering({
    transactions, 
    selectedMonth, 
    setSelectedMonth, 
    searchQuery, 
    setFilteredTransactions
  });

  // 트랜잭션 작업 - 단순화된 버전
  const { 
    deleteTransaction 
  } = useTransactionsOperations(transactions);

  // 이벤트 리스너 - 메모리 누수 방지 버전
  useTransactionsEvents(loadTransactions, refreshKey);

  // 데이터 강제 새로고침 - 성능 최적화
  const refreshTransactions = useCallback(() => {
    console.log('[트랜잭션 코어] 강제 새로고침');
    setRefreshKey(prev => prev + 1);
    loadTransactions();
  }, [loadTransactions, setRefreshKey]);

  return {
    // 데이터
    transactions: filteredTransactions,
    allTransactions: transactions,
    
    // 상태
    isLoading,
    error,
    totalBudget,
    
    // 필터링
    selectedMonth,
    searchQuery,
    setSearchQuery,
    handlePrevMonth,
    handleNextMonth,
    
    // 작업
    deleteTransaction,
    
    // 합계
    totalExpenses: getTotalExpenses(filteredTransactions),
    
    // 새로고침
    refreshTransactions
  };
};
