// 仪表盘页面
// 依据：02-architecture-design.md §3.1 路由结构、§15 仪表盘设计
// 路由：/parent/dashboard
// - 多子女并列展示 ChildSummaryCard
// - 顶部关注横幅（逾期作业 / 出勤率低预警）
// - 当前选中子女的考勤日历

"use client";

import { useState, useCallback, useEffect } from "react";
import { useChildSwitcher } from "@/hooks/useChildSwitcher";
import { useChildSummary } from "@/hooks/useChildSummary";
import { useChildAttendance } from "@/hooks/useChildAttendance";
import { ChildSummaryCard } from "@/components/ChildSummaryCard";
import { AttendanceCalendar } from "@/components/AttendanceCalendar";
import { ParentAttentionBanner } from "@/components/ParentAttentionBanner";
import type { ChildInfo, ChildSummary } from "@/types";

export default function DashboardPage() {
  const { children, currentChild, loading } = useChildSwitcher();
  const { attendance, loading: attLoading } = useChildAttendance();
  const [summaries, setSummaries] = useState<Record<string, ChildSummary>>({});

  const handleSummaryLoaded = useCallback(
    (childId: string, summary: ChildSummary) => {
      setSummaries((prev) => {
        if (prev[childId]?.avgScore === summary.avgScore) return prev;
        return { ...prev, [childId]: summary };
      });
    },
    [],
  );

  if (loading) {
    return (
      <div className="space-y-4">
        <span className="skeleton h-8 w-full rounded" />
        <span className="skeleton h-32 w-full rounded" />
        <span className="skeleton h-48 w-full rounded" />
      </div>
    );
  }

  if (children.length === 0) {
    return (
      <p className="rounded border border-rule bg-paper-elevated p-4 text-sm text-ink-muted">
        暂无绑定子女
      </p>
    );
  }

  const attentionItems = children.map((c) => ({
    childId: c.id,
    childName: c.name,
    pendingHomeworkCount: summaries[c.id]?.pendingHomeworkCount ?? 0,
    attendanceRate: summaries[c.id]?.attendanceRate ?? 1,
  }));

  return (
    <div className="space-y-6">
      <ParentAttentionBanner items={attentionItems} />

      <h1 className="font-serif text-2xl">学习概览</h1>

      {/* 多子女并列卡片 */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        {children.map((child) => (
          <ChildDashboardCard
            key={child.id}
            child={child}
            onSummaryLoaded={handleSummaryLoaded}
          />
        ))}
      </div>

      {/* 当前选中子女的考勤日历 */}
      {currentChild && (
        <div>
          <h2 className="mb-3 font-serif text-lg">{currentChild.name}的考勤</h2>
          {attLoading ? (
            <span className="skeleton h-64 w-full rounded" />
          ) : (
            <AttendanceCalendar records={attendance} />
          )}
        </div>
      )}
    </div>
  );
}

// 子女仪表盘卡片：独立获取每个子女的 summary
function ChildDashboardCard({
  child,
  onSummaryLoaded,
}: {
  child: ChildInfo;
  onSummaryLoaded: (childId: string, summary: ChildSummary) => void;
}) {
  const { summary, loading, error } = useChildSummary(child.id);

  useEffect(() => {
    if (summary) {
      onSummaryLoaded(child.id, summary);
    }
  }, [summary, child.id, onSummaryLoaded]);

  if (loading) {
    return (
      <div className="space-y-4">
        <h2 className="font-serif text-lg">{child.name}</h2>
        <span className="skeleton h-32 w-full rounded" />
        <span className="skeleton h-48 w-full rounded" />
      </div>
    );
  }

  if (error) {
    return (
      <div>
        <h2 className="mb-2 font-serif text-lg">{child.name}</h2>
        <div className="rounded border border-danger p-4 text-sm text-danger">
          加载失败：{error.message}
        </div>
      </div>
    );
  }

  if (!summary) {
    return (
      <div>
        <h2 className="mb-2 font-serif text-lg">{child.name}</h2>
        <p className="text-sm text-ink-muted">暂无数据</p>
      </div>
    );
  }

  return (
    <div>
      <h2 className="mb-3 font-serif text-lg">{child.name}</h2>
      <ChildSummaryCard summary={summary} />
    </div>
  );
}
