
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { useState, useEffect } from "react";
import Index from "./pages/Index";
import Transactions from "./pages/Transactions";
import Analytics from "./pages/Analytics";
import Settings from "./pages/Settings";
import ProfileManagement from "./pages/ProfileManagement";
import NotificationSettings from "./pages/NotificationSettings";
import SecurityPrivacySettings from "./pages/SecurityPrivacySettings";
import HelpSupport from "./pages/HelpSupport";
import PaymentMethods from "./pages/PaymentMethods";
import NotFound from "./pages/NotFound";
import Login from "./pages/Login";
import Register from "./pages/Register";
import ForgotPassword from "./pages/ForgotPassword";
import SupabaseSettings from "./pages/SupabaseSettings";
import { initSyncSettings } from "./utils/syncUtils";
import { AuthProvider } from "./contexts/auth";
import { BudgetProvider } from "./contexts/BudgetContext";

// 전역 오류 처리
const handleError = (error: any) => {
  console.error("앱 오류 발생:", error);
};

// 오류 발생 시 전역 핸들러에 연결
window.addEventListener('error', (event) => {
  handleError(event.error);
});

window.addEventListener('unhandledrejection', (event) => {
  handleError(event.reason);
});

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 1,
      refetchOnWindowFocus: false,
      meta: {
        // meta 객체를 사용하여 오류 관리
        errorHandler: (error: Error) => {
          console.error("쿼리 오류:", error);
        }
      }
    },
    mutations: {
      // onSettled를 사용하여 완료 시 호출되는 콜백 설정
      onSettled: (_data, error) => {
        if (error) {
          console.error("뮤테이션 오류:", error);
        }
      }
    }
  },
});

const App = () => {
  const [isLoaded, setIsLoaded] = useState(false);
  const [initError, setInitError] = useState<Error | null>(null);

  useEffect(() => {
    // 애플리케이션 초기화 및 로딩 상태 관리
    try {
      // 동기화 설정 초기화
      initSyncSettings();
      
      // 기본 예산 데이터 초기화
      if (!localStorage.getItem('budgetData')) {
        const defaultBudgetData = {
          daily: {
            targetAmount: 40000,
            spentAmount: 0,
            remainingAmount: 40000
          },
          weekly: {
            targetAmount: 280000,
            spentAmount: 0,
            remainingAmount: 280000
          },
          monthly: {
            targetAmount: 1200000,
            spentAmount: 0,
            remainingAmount: 1200000
          }
        };
        localStorage.setItem('budgetData', JSON.stringify(defaultBudgetData));
      }
      
      // 기본 카테고리 예산 설정
      if (!localStorage.getItem('categoryBudgets')) {
        const defaultCategoryBudgets = {
          식비: 400000,
          생활비: 600000,
          교통비: 200000
        };
        localStorage.setItem('categoryBudgets', JSON.stringify(defaultCategoryBudgets));
      }
      
      // 빈 트랜잭션 배열 초기화
      if (!localStorage.getItem('transactions')) {
        localStorage.setItem('transactions', JSON.stringify([]));
      }
      
      setIsLoaded(true);
    } catch (error) {
      console.error('앱 초기화 중 오류 발생:', error);
      setInitError(error instanceof Error ? error : new Error('앱 초기화 중 알 수 없는 오류가 발생했습니다'));
      // 오류가 발생해도 앱 로딩
      setIsLoaded(true);
    }
  }, []);

  if (!isLoaded) {
    return <div className="flex items-center justify-center h-screen">
      <div className="text-center">
        <div className="animate-spin h-8 w-8 border-4 border-neuro-income border-t-transparent rounded-full mx-auto mb-4"></div>
        <p className="text-gray-600">앱을 로딩 중입니다...</p>
      </div>
    </div>;
  }

  if (initError) {
    return <div className="flex items-center justify-center h-screen">
      <div className="text-center max-w-md p-6 neuro-card">
        <h2 className="text-xl font-bold text-red-500 mb-4">앱 로드 오류</h2>
        <p className="text-gray-600 mb-4">{initError.message}</p>
        <button 
          onClick={() => window.location.reload()} 
          className="neuro-button"
        >
          다시 시도
        </button>
      </div>
    </div>;
  }

  return (
    <QueryClientProvider client={queryClient}>
      <TooltipProvider>
        <AuthProvider>
          <BudgetProvider>
            <Toaster />
            <Sonner />
            <BrowserRouter>
              <Routes>
                <Route path="/" element={<Index />} />
                <Route path="/transactions" element={<Transactions />} />
                <Route path="/analytics" element={<Analytics />} />
                <Route path="/settings" element={<Settings />} />
                <Route path="/profile-management" element={<ProfileManagement />} />
                <Route path="/notification-settings" element={<NotificationSettings />} />
                <Route path="/security-privacy-settings" element={<SecurityPrivacySettings />} />
                <Route path="/help-support" element={<HelpSupport />} />
                <Route path="/payment-methods" element={<PaymentMethods />} />
                <Route path="/login" element={<Login />} />
                <Route path="/register" element={<Register />} />
                <Route path="/forgot-password" element={<ForgotPassword />} />
                <Route path="/supabase-settings" element={<SupabaseSettings />} />
                <Route path="*" element={<NotFound />} />
              </Routes>
            </BrowserRouter>
          </BudgetProvider>
        </AuthProvider>
      </TooltipProvider>
    </QueryClientProvider>
  );
};

export default App;
