// 考勤页面
// 依据：02-architecture-design.md §3.1 路由结构
// 路由：/parent/attendance
// - 月份导航（前一月/后一月切换）
// - 聚合出勤率卡片 + 异常预警横幅
// - 月度考勤日历

"use client";

import { useState, useMemo } from "react";
import { useChildAttendance } from "@/hooks/useChildAttendance";
import { useChildSwitcher } from "@/hooks/useChildSwitcher";
import { AttendanceCalendar } from "@/components/AttendanceCalendar";
import { AttendanceRateCard } from "@/components/AttendanceRateCard";
import { AttendanceWarningBanner } from "@/components/AttendanceWarningBanner";

function getCurrentMonth(): string {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
}

export default function AttendancePage() {
  const { currentChild } = useChildSwitcher();
  const [currentMonth, setCurrentMonth] = useState<string>(getCurrentMonth);
  const { attendance, loading, error } = useChildAttendance({
    month: currentMonth,
  });

  const monthLabel = useMemo(() => {
    const [year, month] = currentMonth.split("-");
    return `${year ?? ""}年${parseInt(month ?? "1", 10)}月`;
  }, [currentMonth]);

  if (loading) {
    return <span className="skeleton h-64 w-full rounded" />;
  }

  if (error) {
    return (
      <div className="rounded border border-danger p-4 text-sm text-danger">
        加载失败：{error.message}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <h1 className="font-serif text-2xl">{currentChild?.name}的考勤</h1>

      <AttendanceRateCard records={attendance} />

      <AttendanceWarningBanner records={attendance} />

      <AttendanceCalendar
        records={attendance}
        month={currentMonth}
        onMonthChange={setCurrentMonth}
      />

      <p className="text-xs text-ink-muted">
        当前查看：{monthLabel}
      </p>
    </div>
  );
}
