import { useState, useEffect } from 'react';
import { UserProvider, useUser } from './context/UserContext';
import { ProjectProvider, useProject } from './context/ProjectContext';
import { LoginPage } from './pages/LoginPage';
import { ProjectSelectionPage } from './pages/ProjectSelectionPage';
import { TaskSetupPage } from './pages/TaskSetupPage';
import { ActivityPage } from './pages/ActivityPage';
import { TaskSolverPage } from './pages/TaskSolverPage';
import { api } from './api/client';
import type { Task } from './types';

function AppContent() {
  const { user, isLoading: userLoading } = useUser();
  const { currentProject } = useProject();
  const [taskSetupComplete, setTaskSetupComplete] = useState<boolean | null>(null);
  const [checkingTasks, setCheckingTasks] = useState(false);
  const [activeTask, setActiveTask] = useState<Task | null>(null);

  // Check if project has tasks (for owner flow)
  useEffect(() => {
    if (!currentProject || !user) {
      setTaskSetupComplete(null);
      return;
    }

    // Members skip task setup
    if (currentProject.role !== 'owner') {
      setTaskSetupComplete(true);
      return;
    }

    // Owners: check if tasks exist
    const checkTasks = async () => {
      setCheckingTasks(true);
      try {
        const result = await api.listTasks(currentProject.id);
        setTaskSetupComplete((result.tasks?.length || 0) > 0);
      } catch {
        // If error, assume setup not complete
        setTaskSetupComplete(false);
      } finally {
        setCheckingTasks(false);
      }
    };

    checkTasks();
  }, [currentProject, user]);

  // Show loading state while checking for stored user
  if (userLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center">
        <div className="text-white text-xl">Loading...</div>
      </div>
    );
  }

  // No user → Login
  if (!user) {
    return <LoginPage />;
  }

  // User but no project → Project Selection
  if (!currentProject) {
    return <ProjectSelectionPage />;
  }

  // Checking tasks status
  if (checkingTasks || taskSetupComplete === null) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center">
        <div className="text-white text-xl">Loading project...</div>
      </div>
    );
  }

  // Owner + no tasks → Task Setup
  if (currentProject.role === 'owner' && !taskSetupComplete) {
    return <TaskSetupPage onComplete={() => setTaskSetupComplete(true)} />;
  }

  // Active task → Task Solver Page
  if (activeTask) {
    return (
      <TaskSolverPage
        task={activeTask}
        onBack={() => setActiveTask(null)}
        onTaskCompleted={() => setActiveTask(null)}
      />
    );
  }

  // User + Project + Tasks → Activity Page
  return <ActivityPage onStartTask={setActiveTask} />;
}

function App() {
  return (
    <UserProvider>
      <ProjectProvider>
        <AppContent />
      </ProjectProvider>
    </UserProvider>
  );
}

export default App;
