import { useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { App as AntApp, ConfigProvider, theme, Spin } from 'antd';
import { useAuthStore } from '@/stores/auth.store';
import ProtectedRoute from '@/components/ProtectedRoute';
import AppLayout from '@/components/AppLayout';
import LoginPage from '@/pages/LoginPage';
import DashboardPage from '@/pages/DashboardPage';
import InstanceListPage from '@/pages/InstanceListPage';
import CreateWizardPage from '@/pages/CreateWizardPage';
import InstanceDetailPage from '@/pages/InstanceDetailPage';
import RegisterInstancePage from '@/pages/RegisterInstancePage';
import AgentRegistrationsPage from '@/pages/AgentRegistrationsPage';
import InviteCodesPage from '@/pages/InviteCodesPage';
import BackupsPage from '@/pages/BackupsPage';
import AuditLogPage from '@/pages/AuditLogPage';
import SettingsPage from '@/pages/SettingsPage';

export default function App() {
  const { hydrate, isLoading } = useAuthStore();

  useEffect(() => {
    hydrate();
  }, []);

  if (isLoading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <ConfigProvider
      theme={{
        algorithm: theme.darkAlgorithm,
        token: {
          colorPrimary: '#1677ff',
          colorBgBase: '#141414',
          borderRadius: 6,
        },
      }}
    >
      <AntApp>
        <BrowserRouter>
          <Routes>
            <Route path="/login" element={<LoginPage />} />

            <Route
              path="/app"
              element={
                <ProtectedRoute>
                  <AppLayout />
                </ProtectedRoute>
              }
            >
              <Route index element={<DashboardPage />} />
              <Route path="instances" element={<InstanceListPage />} />
              <Route path="instances/new" element={<CreateWizardPage />} />
              <Route path="instances/register" element={<RegisterInstancePage />} />
              <Route path="instances/:id" element={<InstanceDetailPage />} />
              <Route path="agents/registrations" element={<AgentRegistrationsPage />} />
              <Route path="agents/invite-codes" element={<InviteCodesPage />} />
              <Route path="backups" element={<BackupsPage />} />
              <Route path="audit" element={<AuditLogPage />} />
              <Route path="settings" element={<SettingsPage />} />
            </Route>

            <Route path="*" element={<Navigate to="/app" replace />} />
          </Routes>
        </BrowserRouter>
      </AntApp>
    </ConfigProvider>
  );
}
