import { useState, useEffect } from 'react';
import { HashRouter, Routes, Route } from 'react-router-dom';
import { Layout } from '@/components/layout';
import { Dashboard, Todo, Kuntae, Jobreport, Project, Login, CommonCodePage, ItemsPage, UserListPage, MonthlyWorkPage, MailFormPage, UserAuthPage, Note } from '@/pages';
import { PatchList } from '@/pages/PatchList';
import { BugReport } from '@/pages/BugReport';
import { MailList } from '@/pages/MailList';
import { Customs } from '@/pages/Customs';
import { LicenseList } from '@/components/license/LicenseList';
import { PartList } from '@/pages/PartList';
import HolidayRequest from '@/pages/HolidayRequest';
import { comms } from '@/communication';
import { UserInfo } from '@/types';
import { Loader2 } from 'lucide-react';
import { ThemeProvider } from '@/context/ThemeContext';

export default function App() {
  const [isConnected, setIsConnected] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState<boolean | null>(null); // null = 체크 중
  const [user, setUser] = useState<UserInfo | null>(null);

  useEffect(() => {
    // 통신 상태 구독
    const unsubscribe = comms.subscribe((msg: unknown) => {
      const message = msg as { type?: string; connected?: boolean };
      if (message?.type === 'CONNECTION_STATE') {
        setIsConnected(message.connected ?? false);
        // 연결되면 로그인 상태 체크
        if (message.connected) {
          checkLoginStatus();
        }
      }
    });

    // 초기 연결 상태 설정
    setIsConnected(comms.getConnectionState());

    // 연결되어 있으면 바로 로그인 상태 체크
    if (comms.getConnectionState()) {
      checkLoginStatus();
    }

    return () => {
      unsubscribe();
    };
  }, []);

  const checkLoginStatus = async () => {
    try {
      const result = await comms.checkLoginStatus();
      if (result.Success) {
        setIsLoggedIn(result.IsLoggedIn);
        setUser(result.User);
      } else {
        setIsLoggedIn(false);
        setUser(null);
      }
    } catch (err) {
      console.error('로그인 상태 체크 실패:', err);
      setIsLoggedIn(false);
      setUser(null);
    }
  };

  const handleLoginSuccess = () => {
    checkLoginStatus();
  };

  // 로그인 상태 체크 중
  if (isLoggedIn === null) {
    return (
      <div className="min-h-screen gradient-bg flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-10 h-10 text-white animate-spin mx-auto mb-4" />
          <p className="text-white/70">로그인 상태 확인 중...</p>
        </div>
      </div>
    );
  }

  // 로그인 안됨 → 로그인 화면 표시
  if (!isLoggedIn) {
    return <Login onLoginSuccess={handleLoginSuccess} />;
  }

  // 로그인 됨 → 메인 앱 표시
  return (
    <ThemeProvider>
      <HashRouter>
        <Routes>
          <Route element={<Layout isConnected={isConnected} user={user} />}>
            <Route path="/" element={<Dashboard />} />
            <Route path="/dashboard" element={<Dashboard />} />
            <Route path="/todo" element={<Todo />} />
            <Route path="/kuntae" element={<Kuntae />} />
            <Route path="/holiday-request" element={<HolidayRequest />} />
            <Route path="/jobreport" element={<Jobreport />} />
            <Route path="/project" element={<Project />} />
            <Route path="/common" element={<CommonCodePage />} />
            <Route path="/items" element={<ItemsPage />} />
            <Route path="/customs" element={<Customs />} />
            <Route path="/user/list" element={<UserListPage />} />
            <Route path="/user/auth" element={<UserAuthPage />} />
            <Route path="/monthly-work" element={<MonthlyWorkPage />} />
            <Route path="/mail-form" element={<MailFormPage />} />
            <Route path="/note" element={<Note />} />
            <Route path="/patch-list" element={<PatchList />} />
            <Route path="/bug-report" element={<BugReport />} />
            <Route path="/mail-list" element={<MailList />} />
            <Route path="/license" element={<LicenseList />} />
            <Route path="/partlist" element={<PartList />} />
          </Route>
        </Routes>
        {/* Tailwind Breakpoint Indicator - 개발용 */}
        <div className="fixed bottom-2 right-2 z-50 bg-black/80 text-white text-xs px-2 py-1 rounded font-mono">
          <span className="sm:hidden">XS</span>
          <span className="hidden sm:inline md:hidden">SM</span>
          <span className="hidden md:inline lg:hidden">MD</span>
          <span className="hidden lg:inline xl:hidden">LG</span>
          <span className="hidden xl:inline 2xl:hidden">XL</span>
          <span className="hidden 2xl:inline">2XL</span>
        </div>
      </HashRouter>
    </ThemeProvider>
  );
}
