import dayjs from "dayjs";
import { Calendar } from "@arco-design/web-react";
import "./index.css";

const CalendarTaskModule = ({ tasks = [], selectedDate, onDateChange }) => {
  // 格式化今天的日期
  const today = new Date();
  const formattedToday = `${today.getFullYear()}-${String(
    today.getMonth() + 1
  ).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;

  // 获取有任务的日期集合
  const datesWithTasks = new Set(tasks?.map((task) => task.date) || []);

  // 日历单元格渲染函数
  const dateRender = (current) => {
    const dateStr = current.format("YYYY-MM-DD");
    const hasTasks = datesWithTasks.has(dateStr); // 存在任务
    const isCurrentDay = dateStr === dayjs(selectedDate).format("YYYY-MM-DD");
    const isToday = dateStr === formattedToday;

    return (
      <div
        className={`calendar-date-cell ${hasTasks ? "has-tasks" : ""} ${
          isCurrentDay ? "is-current-day" : ""
        } ${isToday ? "is-today" : ""}`}
      >
        <div className="date-number">{current.date()}</div>
        {hasTasks && <div className="task-dot"></div>}
      </div>
    );
  };

  const handleDateChange = (date, dateString) => {
    if (onDateChange) {
      // Arco Calendar passes a dayjs object
      if (date && date.format) {
        // Convert dayjs to Date object
        const dateStr = date.format("YYYY-MM-DD");
        const dateObj = new Date(dateStr + "T00:00:00");
        if (!isNaN(dateObj.getTime())) {
          onDateChange(dateObj);
        }
      } else if (dateString) {
        // Fallback to dateString if available
        const dateObj = new Date(dateString + "T00:00:00");
        if (!isNaN(dateObj.getTime())) {
          onDateChange(dateObj);
        }
      }
    }
  };

  return (
    <div className="module-calendar-task-wrapper">
      <Calendar
        panelWidth="300"
        panel
        defaultValue={formattedToday}
        value={
          selectedDate
            ? selectedDate.toISOString().split("T")[0]
            : formattedToday
        }
        style={{ fontSize: "18px" }}
        onChange={handleDateChange}
        dateRender={dateRender}
      />
    </div>
  );
};

export default CalendarTaskModule;
