import { useState, useEffect } from "react";
import StartClass from "./components/StartClass";
import QuickAccess from "./components/QuickAccess";
import CalendarTaskModule from "./components/CalendarTaskModule";
import StudyStatus from "./components/StudyStatus";
import Rank from "@/components/Rank";
import StageProgress from "@/components/StageProgress";
import TaskList from "./components/TaskList";
import { getDashboardStatistics } from "@/services";
import "./index.css";

const Dashboard = () => {
  const [dashboardData, setDashboardData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [selectedDate, setSelectedDate] = useState(new Date());

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

  // 获取仪表板完整数据
  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      const response = await getDashboardStatistics();
      if (response && response.success) {
        setDashboardData(response.data);
      } else if (response) {
        // 兼容直接返回数据的情况
        setDashboardData(response);
      }
    } catch (error) {
      console.error('Failed to fetch dashboard data:', error);
    } finally {
      setLoading(false);
    }
  };

  // 根据选中日期筛选任务
  const getTasksForDate = (date) => {
    if (!dashboardData?.tasks?.allTasks) return [];
    // Check if date is valid before calling toISOString
    if (!date || isNaN(date.getTime())) {
      console.warn('Invalid date provided to getTasksForDate:', date);
      return [];
    }
    const dateStr = date.toISOString().split('T')[0];
    return dashboardData.tasks.allTasks.filter(task => task.date === dateStr);
  };

  return (
    <div className="dashboard">
      <StageProgress showBlockageAlert={true} />

      <div className="dashboard-grid">
        <StartClass 
          courses={dashboardData?.courses}
          tasks={dashboardData?.tasks}
          loading={loading}
        />
        <QuickAccess />
        <CalendarTaskModule 
          tasks={dashboardData?.tasks?.allTasks}
          selectedDate={selectedDate}
          onDateChange={setSelectedDate}
          loading={loading}
        />
        <StudyStatus 
          progress={dashboardData?.overview?.overallProgress}
          loading={loading}
        />
        <Rank 
          data={dashboardData?.ranking ? {
            rankings: dashboardData.ranking.topStudents
          } : null}
          loading={loading}
        />
        <TaskList 
          tasks={getTasksForDate(selectedDate)}
          selectedDate={selectedDate}
          loading={loading}
        />
      </div>
    </div>
  );
};

export default Dashboard;
