import { useState, useEffect, useCallback } from 'react'; import { BudgetData, BudgetPeriod } from '../types'; import { loadBudgetDataFromStorage, saveBudgetDataToStorage, clearAllBudgetData } from '../storage'; import { toast } from '@/components/ui/use-toast'; import { calculateUpdatedBudgetData, calculateSpentAmounts } from '../budgetUtils'; // 예산 데이터 상태 관리 훅 export const useBudgetDataState = (transactions: any[]) => { const [budgetData, setBudgetData] = useState(loadBudgetDataFromStorage()); const [selectedTab, setSelectedTab] = useState("daily"); const [isInitialized, setIsInitialized] = useState(false); // 초기 로드 및 이벤트 리스너 설정 useEffect(() => { const loadBudget = () => { try { console.log('예산 데이터 로드 시도 중...'); const loadedData = loadBudgetDataFromStorage(); console.log('예산 데이터 로드됨:', loadedData); setBudgetData(loadedData); // 최근 데이터 로드 시간 기록 localStorage.setItem('lastBudgetDataLoadTime', new Date().toISOString()); if (!isInitialized) { setIsInitialized(true); } } catch (error) { console.error('예산 데이터 로드 중 오류:', error); } }; // 초기 로드 loadBudget(); // 이벤트 리스너 설정 const handleBudgetUpdate = (e?: StorageEvent) => { console.log('예산 데이터 업데이트 이벤트 감지:', e?.key); if (!e || e.key === 'budgetData' || e.key === null) { loadBudget(); } }; window.addEventListener('budgetDataUpdated', () => handleBudgetUpdate()); window.addEventListener('storage', handleBudgetUpdate); window.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { console.log('페이지 보임: 예산 데이터 새로고침'); loadBudget(); } }); window.addEventListener('focus', () => { console.log('창 포커스: 예산 데이터 새로고침'); loadBudget(); }); // 주기적 데이터 검사 (1초마다) const intervalId = setInterval(() => { const lastSaveTime = localStorage.getItem('lastBudgetSaveTime'); const lastLoadTime = localStorage.getItem('lastBudgetDataLoadTime'); if (lastSaveTime && lastLoadTime && new Date(lastSaveTime) > new Date(lastLoadTime)) { console.log('새로운 저장 감지됨, 데이터 다시 로드...'); loadBudget(); } }, 1000); return () => { window.removeEventListener('budgetDataUpdated', () => handleBudgetUpdate()); window.removeEventListener('storage', handleBudgetUpdate); window.removeEventListener('visibilitychange', () => {}); window.removeEventListener('focus', () => loadBudget()); clearInterval(intervalId); }; }, [isInitialized]); // 트랜잭션 변경 시 지출 금액 업데이트 useEffect(() => { if (transactions.length > 0) { console.log('트랜잭션 변경으로 인한 예산 데이터 업데이트. 트랜잭션 수:', transactions.length); try { // 지출 금액 업데이트 const updatedBudgetData = calculateSpentAmounts(transactions, budgetData); // 상태 및 스토리지 모두 업데이트 setBudgetData(updatedBudgetData); saveBudgetDataToStorage(updatedBudgetData); // 저장 시간 업데이트 localStorage.setItem('lastBudgetSaveTime', new Date().toISOString()); } catch (error) { console.error('예산 데이터 업데이트 중 오류:', error); } } }, [transactions, budgetData]); // 예산 목표 업데이트 함수 const handleBudgetGoalUpdate = useCallback(( type: BudgetPeriod, amount: number, newCategoryBudgets?: Record ) => { try { console.log(`예산 목표 업데이트: ${type}, 금액: ${amount}`); // 월간 예산 직접 업데이트 (카테고리 예산이 없는 경우) if (!newCategoryBudgets) { const updatedBudgetData = calculateUpdatedBudgetData(budgetData, type, amount); console.log('새 예산 데이터:', updatedBudgetData); setBudgetData(updatedBudgetData); saveBudgetDataToStorage(updatedBudgetData); // 저장 시간 업데이트 localStorage.setItem('lastBudgetSaveTime', new Date().toISOString()); } } catch (error) { console.error('예산 목표 업데이트 중 오류:', error); toast({ title: "예산 업데이트 실패", description: "예산 목표를 업데이트하는데 문제가 발생했습니다.", variant: "destructive" }); } }, [budgetData]); // 예산 데이터 초기화 함수 const resetBudgetData = useCallback(() => { try { console.log('예산 데이터 초기화'); clearAllBudgetData(); setBudgetData(loadBudgetDataFromStorage()); } catch (error) { console.error('예산 데이터 초기화 중 오류:', error); toast({ title: "예산 초기화 실패", description: "예산 데이터를 초기화하는데 문제가 발생했습니다.", variant: "destructive" }); } }, []); // 예산 데이터 변경 시 로그 기록 useEffect(() => { console.log('최신 예산 데이터:', budgetData); }, [budgetData]); return { budgetData, selectedTab, setSelectedTab, handleBudgetGoalUpdate, resetBudgetData }; };