import React, { useEffect } from 'react';
import { useStore } from './store/useStore';
import { getCurrentUser, getProjects } from './lib/api';
import { Sidebar } from './components/Sidebar';
import { Dashboard } from './components/Dashboard';
import { ProjectLibrary } from './components/ProjectLibrary';
import { VideoWorkspace } from './components/VideoWorkspace';
import { TemplateRegistry } from './components/TemplateRegistry';
import { AISegmentation } from './components/AISegmentation';
import { Login } from './components/Login';
import { UserAdmin } from './components/UserAdmin';

export type ActiveModule = 'dashboard' | 'projects' | 'ai' | 'workspace' | 'templates' | 'admin';

export default function App() {
  const isAuthenticated = useStore((state) => state.isAuthenticated);
  const activeModule = useStore((state) => state.activeModule);
  const setActiveModule = useStore((state) => state.setActiveModule);
  const setProjects = useStore((state) => state.setProjects);
  const setError = useStore((state) => state.setError);
  const setCurrentUser = useStore((state) => state.setCurrentUser);
  const logout = useStore((state) => state.logout);
  const currentUser = useStore((state) => state.currentUser);

  useEffect(() => {
    if (isAuthenticated) {
      Promise.all([getCurrentUser(), getProjects()])
        .then(([user, projects]) => {
          setCurrentUser(user);
          setProjects(projects);
        })
        .catch((err) => {
          console.error('Failed to fetch projects:', err);
          if (err?.response?.status === 401) {
            logout();
            return;
          }
          setError('获取项目列表失败');
        });
    }
  }, [isAuthenticated, logout, setCurrentUser, setProjects, setError]);

  if (!isAuthenticated) {
    return <Login />;
  }

  return (
    <div className="flex h-screen w-full bg-[#0a0a0a] text-gray-200 overflow-hidden font-sans">
      <Sidebar activeModule={activeModule as ActiveModule} setActiveModule={setActiveModule} />
      <main className="flex-1 flex flex-col min-w-0 h-full relative">
        {activeModule === 'dashboard' && <Dashboard />}
        {activeModule === 'projects' && <ProjectLibrary onProjectSelect={() => setActiveModule('workspace')} />}
        {activeModule === 'ai' && <AISegmentation onSendToWorkspace={() => setActiveModule('workspace')} />}
        {activeModule === 'workspace' && <VideoWorkspace onNavigateToAI={() => setActiveModule('ai')} />}
        {activeModule === 'templates' && <TemplateRegistry />}
        {activeModule === 'admin' && currentUser?.role === 'admin' && <UserAdmin />}
      </main>
    </div>
  );
}
