
import { useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { ProjectList } from './components/ProjectList';
import { ProjectForm } from './components/ProjectForm';
import { ProjectDetails } from './pages/ProjectDetails';
import Models from './pages/Models';
import ModelDetail from './pages/ModelDetail';

import AiClassificationSettings from './pages/AiClassificationSettings';
import TemplateManagement from './pages/TemplateManagement';
import { MaterialModelBinding } from './pages/MaterialModelBinding';
import Tools from './pages/Tools';
import DataCleaningTool from './pages/tools/DataCleaningTool';
import JsonParserTool from './pages/tools/JsonParserTool';
import DebugPanelTool from './pages/tools/DebugPanelTool';
import ChatTool from './pages/tools/ChatTool';
import ChatTestPage from './pages/tools/ChatTestPage';
import WatermarkTool from './pages/tools/WatermarkTool';
import SimilaritySearchTool from './pages/tools/SimilaritySearchTool';
import BatchThumbnailGenerator from './pages/tools/BatchThumbnailGenerator';
import OutfitRecommendationTool from './pages/tools/OutfitRecommendationTool';
import AdvancedFilterTool from './pages/tools/AdvancedFilterTool';
import OutfitSearchTool from './pages/tools/OutfitSearchTool';
import OutfitFavoritesTool from './pages/tools/OutfitFavoritesTool';
import OutfitComparisonTool from './pages/tools/OutfitComparisonTool';
import MaterialSearchTool from './pages/tools/MaterialSearchTool';
import ImageGenerationTool from './pages/tools/ImageGenerationTool';
import ImageEditingTool from './pages/tools/ImageEditingTool';
import VoiceGenerationHistory from './pages/tools/VoiceGenerationHistory';
import VideoGenerationTool from './pages/tools/VideoGenerationTool';
import SimpleHedraLipSyncTool from './pages/tools/SimpleHedraLipSyncTool';
import HedraLipSyncRecords from './pages/tools/HedraLipSyncRecords';
import OmniHumanDetectionTool from './pages/tools/OmniHumanDetectionTool';
import { EnrichedAnalysisDemo } from './pages/tools/EnrichedAnalysisDemo';
import MaterialCenter from './pages/MaterialCenter';
import VideoGeneration from './pages/VideoGeneration';
import { OutfitPhotoGenerationPage } from './pages/OutfitPhotoGeneration';
import ComfyUIManagement from './pages/ComfyUIManagement';
import ComfyUIWorkflowTest from './pages/ComfyUIWorkflowTest';
import { WorkflowPage } from './pages/WorkflowPage';
// import CanvasTool from './pages/CanvasTool';

import Navigation from './components/Navigation';
import { NotificationSystem, useNotifications } from './components/NotificationSystem';
import { useProjectStore } from './store/projectStore';
import { useUIStore } from './store/uiStore';
import { CreateProjectRequest, UpdateProjectRequest } from './types/project';
import { screenAdaptationService } from './services/screenAdaptationService';
import "./App.css";
import './styles/design-system.css';
import './styles/animations.css';
/**
 * 主应用组件
 * 遵循 Tauri 开发规范的应用架构设计
 */
function App() {
  const { createProject, updateProject } = useProjectStore();
  const {
    showCreateProjectModal,
    showEditProjectModal,
    editingProject,
    closeCreateProjectModal,
    closeEditProjectModal
  } = useUIStore();

  // 通知系统
  const { notifications, removeNotification, success, error } = useNotifications();

  // 屏幕适配
  useEffect(() => {
    const initScreenAdaptation = async () => {
      try {
        await screenAdaptationService.applySmartAdaptation();
        console.log('屏幕适配初始化完成');
      } catch (error) {
        console.error('屏幕适配初始化失败:', error);
      }
    };

    initScreenAdaptation();
  }, []);

  // 处理创建项目
  const handleCreateProject = async (data: CreateProjectRequest) => {
    try {
      await createProject(data);
      success('项目创建成功', `项目"${data.name}"已创建`);
      closeCreateProjectModal();
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '未知错误';
      error('项目创建失败', errorMessage);
      throw err;
    }
  };

  // 处理更新项目
  const handleUpdateProject = async (data: UpdateProjectRequest) => {
    if (!editingProject) return;

    try {
      await updateProject(editingProject.id, data);
      success('项目更新成功', `项目"${data.name}"已更新`);
      closeEditProjectModal();
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '未知错误';
      error('项目更新失败', errorMessage);
      throw err;
    }
  };

  return (
    <Router>
      <div className="h-screen flex flex-col bg-gradient-to-br from-gray-50 via-white to-gray-50">
        {/* 固定的导航栏 */}
        <Navigation />

        {/* 可滚动的主要内容区域 */}
        <main className="flex-1 overflow-y-auto smooth-scroll">
          <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-6 lg:py-8 max-w-full">
            <Routes>
              <Route path="/" element={<ProjectList />} />
              <Route path="/projects" element={<ProjectList />} />
              {/* AI 画布工具暂时隐藏 */}
              {/* <Route path="/canvas-tool" element={<CanvasTool />} /> */}
              <Route path="/project/:id" element={<ProjectDetails />} />
              <Route path="/models" element={<Models />} />
              <Route path="/models/:id" element={<ModelDetail />} />
              <Route path="/ai-classification-settings" element={<AiClassificationSettings />} />
              <Route path="/templates" element={<TemplateManagement />} />
              <Route path="/material-model-binding" element={<MaterialModelBinding />} />
              <Route path="/fashion-chat" element={<ChatTool />} />
              <Route path="/outfit" element={<OutfitRecommendationTool />} />
              <Route path="/material-center" element={<MaterialCenter />} />
              <Route path="/video-generation" element={<VideoGeneration />} />
              <Route path="/video-generation/:projectId" element={<VideoGeneration />} />
              <Route path="/outfit-photo-generation" element={<OutfitPhotoGenerationPage />} />
              <Route path="/outfit-photo-generation/:projectId" element={<OutfitPhotoGenerationPage />} />
              <Route path="/outfit-photo-generation/:projectId/:modelId" element={<OutfitPhotoGenerationPage />} />

              <Route path="/workflows" element={<WorkflowPage />} />
              <Route path="/comfyui-cluster" element={<ComfyUIManagement />} />
              <Route path="/comfyui-node" element={<ComfyUIWorkflowTest />} />
              <Route path="/tools" element={<Tools />} />
              <Route path="/tools/data-cleaning" element={<DataCleaningTool />} />
              <Route path="/tools/json-parser" element={<JsonParserTool />} />
              <Route path="/tools/debug-panel" element={<DebugPanelTool />} />
              <Route path="/tools/ai-chat" element={<ChatTool />} />
              <Route path="/tools/chat-test" element={<ChatTestPage />} />
              <Route path="/tools/watermark" element={<WatermarkTool />} />
              <Route path="/tools/similarity-search" element={<SimilaritySearchTool />} />
              <Route path="/tools/batch-thumbnail-generator" element={<BatchThumbnailGenerator />} />
              <Route path="/tools/outfit-recommendation" element={<OutfitRecommendationTool />} />
              <Route path="/tools/outfit-search" element={<OutfitSearchTool />} />
              <Route path="/tools/outfit-favorites" element={<OutfitFavoritesTool />} />
              <Route path="/tools/outfit-comparison" element={<OutfitComparisonTool />} />
              <Route path="/tools/material-search" element={<MaterialSearchTool />} />
              <Route path="/tools/image-generation" element={<ImageGenerationTool />} />
              <Route path="/tools/image-editing" element={<ImageEditingTool />} />
              <Route path="/tools/voice-generation-history" element={<VoiceGenerationHistory />} />
              <Route path="/tools/voice-clone" element={<VoiceGenerationHistory />} />
              <Route path="/tools/volcano-video-generation" element={<VideoGenerationTool />} />
              <Route path="/tools/hedra-lip-sync" element={<SimpleHedraLipSyncTool />} />
              <Route path="/tools/simple-hedra-lip-sync" element={<SimpleHedraLipSyncTool />} />
              <Route path="/tools/hedra-records" element={<HedraLipSyncRecords />} />
              <Route path="/tools/omni-human-detection" element={<OmniHumanDetectionTool />} />
              <Route path="/tools/advanced-filter-demo" element={<AdvancedFilterTool />} />
              <Route path="/tools/enriched-analysis-demo" element={<EnrichedAnalysisDemo />} />
            </Routes>
          </div>
        </main>

        {/* 创建项目模态框 */}
        {showCreateProjectModal && (
          <ProjectForm
            onSubmit={handleCreateProject}
            onCancel={closeCreateProjectModal}
          />
        )}

        {/* 编辑项目模态框 */}
        {showEditProjectModal && editingProject && (
          <ProjectForm
            initialData={editingProject}
            onSubmit={handleUpdateProject}
            onCancel={closeEditProjectModal}
            isEdit={true}
          />
        )}

        {/* 通知系统 */}
        <NotificationSystem
          notifications={notifications}
          onRemove={removeNotification}
          position="top-right"
          maxNotifications={5}
        />

        {/* Modal 渲染容器 - 独立于主布局，避免复杂容器结构影响 */}
        <div id="modal-root" className="modal-root-container"></div>
      </div>
    </Router>
  );
}

export default App;
