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 ClassRank from "@/components/ClassRank";
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 getTime
    if (!date || isNaN(date.getTime())) {
      console.warn("Invalid date provided to getTasksForDate:", date);
      return [];
    }
    // 使用本地日期格式，避免时区问题
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const dateStr = `${year}-${month}-${day}`;
    
    console.log("Looking for tasks on date:", dateStr);
    const tasks = dashboardData.tasks.allTasks.filter((task) => task.date === dateStr);
    console.log("Found tasks:", tasks);
    
    return tasks;
  };

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

      <div className="dashboard-wrapper">
        <div className="dashboard-left-content">
          <StartClass
            courses={dashboardData?.courses}
            tasks={dashboardData?.tasks}
            loading={loading}
          />
          <QuickAccess />
          <div className="status-rank-wrapper">
            <StudyStatus
              progress={dashboardData?.overview?.overallProgress}
              loading={loading}
            />
            <ClassRank
              className="class-rank-wrapper"
              data={
                dashboardData?.ranking
                  ? {
                      rankings: dashboardData.ranking.topStudents,
                    }
                  : null
              }
            />
          </div>
        </div>
        <div className="dashboard-right-content">
          <CalendarTaskModule
            tasks={dashboardData?.tasks?.allTasks}
            selectedDate={selectedDate}
            onDateChange={setSelectedDate}
          />
          <TaskList tasks={getTasksForDate(selectedDate)} loading={loading} />
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
