import { useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { ConfigProvider, App as AntApp, Spin } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import AdminLayout from './pages/AdminLayout';
import AdminAuthoriz from './pages/AdminAuthoriz';
import AdminConsume from './pages/AdminConsume';
import AdminLoginPage from './pages/AdminLoginPage';
import AdminDashboard from './pages/AdminDashboard';
import AdminPlatform from './pages/AdminPlatform';
import AdminUsers from './pages/AdminUsers';
import AdminTeams from './pages/AdminTeams';
import AdminModels from './pages/AdminModels';
import AdminSettings from './pages/AdminSettings';
import AdminNotificationManager from './pages/AdminNotificationManager';
import AdminCreditRecords from './pages/AdminCreditRecords';
import AdminPaymentConfig from './pages/AdminPaymentConfig';
import AdminPaymentStats from './pages/AdminPaymentStats';
import AdminIndustries from './pages/AdminIndustries';
import AdminVideoEngines from './pages/AdminVideoEngines';
import AdminImageEngines from './pages/AdminImageEngines';
import AdminCreditRatios from './pages/AdminCreditRatios';
import AdminMenuConfig from './pages/AdminMenuConfig';
import AdminCreditProducts from './pages/AdminCreditProducts';
import AdminLlmBillingPolicies from './pages/AdminLlmBillingPolicies';
import AdminLlmBillingExecutions from './pages/AdminLlmBillingExecutions';
import AdminOperationLogs from './pages/AdminOperationLogs';
import AdminOauthAppList from './pages/AdminOauthAppList';
import AdminGenerationRecords from './pages/AdminGenerationRecords';
import AdminGenerationAiRecords from './pages/AdminGenerationAiRecords';
import AdminHotOpeningReplications from './pages/AdminHotOpeningReplications';
import AdminHotOpeningReplicationDetail from './pages/AdminHotOpeningReplicationDetail';
import AdminShotReplications from './pages/AdminShotReplications';
import AdminShotTaskSetDetail from './pages/AdminShotTaskSetDetail';
import AdminReplicationProjectDetail from './pages/AdminReplicationProjectDetail';
import AdminVideoPromptSchemaConfig from './pages/AdminVideoPromptSchemaConfig';
import AdminVideoUpscale from './pages/AdminVideoUpscale';
import AdminContactRequests from './pages/AdminContactRequests';
import AdminHomeMaterials from './pages/AdminHomeMaterials';
import AdminPreTestTemplates from './pages/AdminPreTestTemplates';
import AdminOAuthList from './pages/AdminOAuthList';
import AdminMaterialList from './pages/AdminMaterialList';
import AdminPrivatePortraitProjects from './pages/AdminPrivatePortraitProjects';
import AdminApiKeys from './pages/AdminApiKeys';
import AdminApiModelPricings from './pages/AdminApiModelPricings';
import AdminApiUsage from './pages/AdminApiUsage';
import AdminInvoices from './pages/AdminInvoices';
import AdminBankTransactions from './pages/AdminBankTransactions';
import AdminScheduledTasks from './pages/AdminScheduledTasks';

import { useAdminStore } from './store';

const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
  const { user, loading, checkAuth } = useAdminStore();

  useEffect(() => {
    const token = localStorage.getItem('auth_token');
    if (!token && !loading && !user) {
      window.location.href = '/login';
    }
  }, [user, loading]);

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" />
      </div>
    );
  }
  if (!user) {
    window.location.href = '/login';
    return null;
  }
  return <>{children}</>;
};

const App = () => {
  const { checkAuth } = useAdminStore();
  useEffect(() => { checkAuth(); }, []);

  return (
    <ConfigProvider locale={zhCN} theme={{
      token: { colorPrimary: '#6366f1', borderRadius: 8 },
      components: {
        Button: { controlHeight: 36, controlHeightLG: 44 },
        Card: { boxShadow: '0 1px 3px rgba(0,0,0,0.04)' },
        Table: { headerBg: '#fafbfc' },
      },
    }}>
      <AntApp>
        <BrowserRouter>
          <Routes>
            <Route path="/login" element={<AdminLoginPage />} />
            <Route path="/" element={<ProtectedRoute><AdminLayout /></ProtectedRoute>}>
              <Route index element={<AdminDashboard />} />
              <Route path="users" element={<AdminUsers />} />
              <Route path="teams" element={<AdminTeams />} />
              <Route path="credit-records" element={<AdminCreditRecords />} />
              <Route path="models" element={<AdminModels />} />
              <Route path="credit-ratios" element={<AdminCreditRatios />} />
              <Route path="video-engines" element={<AdminVideoEngines />} />
              <Route path="image-engines" element={<AdminImageEngines />} />
              <Route path="industries" element={<AdminIndustries />} />
              <Route path="menu-configs" element={<AdminMenuConfig />} />
              <Route path="credit-products" element={<AdminCreditProducts />} />
              <Route path="llm-billing-policies" element={<AdminLlmBillingPolicies />} />
              <Route path="llm-billing-executions" element={<AdminLlmBillingExecutions />} />
              <Route path="payment" element={<AdminPaymentConfig />} />
              <Route path="payment-stats" element={<AdminPaymentStats />} />
              <Route path="settings" element={<AdminSettings />} />
              <Route path="video-prompt-schema-config" element={<AdminVideoPromptSchemaConfig />} />
              <Route path="video-upscale" element={<AdminVideoUpscale />} />
              <Route path="api-keys" element={<AdminApiKeys />} />
              <Route path="api-model-pricings" element={<AdminApiModelPricings />} />
              <Route path="api-usage" element={<AdminApiUsage />} />
              <Route path="invoices" element={<AdminInvoices />} />
              <Route path="bank-transactions" element={<AdminBankTransactions />} />
              <Route path="scheduled-tasks" element={<AdminScheduledTasks />} />
              <Route path="notifications" element={<AdminNotificationManager />} />
              <Route path="oauthapp-list" element={<AdminOauthAppList />} />
              <Route path="operation-logs" element={<AdminOperationLogs />} />
              <Route path="generation-records" element={<AdminGenerationRecords />} />
              <Route path="generation-ai" element={<AdminGenerationAiRecords />} />
              <Route path="hot-opening-replications" element={<AdminHotOpeningReplications />} />
              <Route path="hot-opening-replications/:projectId" element={<AdminHotOpeningReplicationDetail />} />
              <Route path="shot-replications" element={<AdminShotReplications />} />
              <Route path="shot-replications/task-sets/:taskSetId" element={<AdminShotTaskSetDetail />} />
              <Route path="shot-replications/projects/:projectId" element={<AdminReplicationProjectDetail moduleType="shot_replicate" />} />
              <Route path="authoriza" element={<AdminAuthoriz />} />
              <Route path="consume" element={<AdminConsume />} />
              <Route path="platform" element={<AdminPlatform />} />
              <Route path="contact-requests" element={<AdminContactRequests />} />
              <Route path="home-materials" element={<AdminHomeMaterials />} />
              <Route path="pretest-templates" element={<AdminPreTestTemplates />} />
              <Route path="oauth-list" element={<AdminOAuthList />} />
              <Route path="material-list" element={<AdminMaterialList />} />
              <Route path="private-portrait-projects" element={<AdminPrivatePortraitProjects />} />
            </Route>
            <Route path="*" element={<Navigate to="/" replace />} />
          </Routes>
        </BrowserRouter>
      </AntApp>
    </ConfigProvider>
  );
};

export default App;
