// ChildDetailPanel：子女详情多 Tab 面板
// 依据：02-architecture-design.md §15 组件设计
// - Tab：overview / homework / grades / exams / schedule
// - 受控组件：由父级（页面）管理 activeTab 与 URL 状态

"use client";

import Link from "next/link";
import type { ChildDetail, ScheduleItem } from "@/types";
import { cn } from "@/lib/utils";

export type DetailTab = "overview" | "homework" | "grades" | "exams" | "schedule";

const TABS: { value: DetailTab; label: string }[] = [
  { value: "overview", label: "概览" },
  { value: "homework", label: "作业" },
  { value: "grades", label: "成绩" },
  { value: "exams", label: "考试" },
  { value: "schedule", label: "课表" },
];

const DAY_LABELS = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];

interface ChildDetailPanelProps {
  childDetail: ChildDetail;
  activeTab: DetailTab;
  onTabChange: (tab: DetailTab) => void;
}

export function ChildDetailPanel({
  childDetail,
  activeTab,
  onTabChange,
}: ChildDetailPanelProps) {
  return (
    <div className="space-y-4">
      {/* Tab 导航 */}
      <div
        className="flex gap-1 border-b border-rule"
        role="tablist"
        aria-label="子女详情视图"
      >
        {TABS.map((t) => (
          <button
            key={t.value}
            type="button"
            role="tab"
            aria-selected={activeTab === t.value}
            onClick={() => onTabChange(t.value)}
            className={cn(
              "border-b-2 px-4 py-2 text-sm transition-colors",
              activeTab === t.value
                ? "border-accent font-medium"
                : "border-transparent text-ink-muted hover:text-ink",
            )}
          >
            {t.label}
          </button>
        ))}
      </div>

      {/* Tab 内容 */}
      <div role="tabpanel">
        {activeTab === "overview" && <OverviewTab childDetail={childDetail} />}
        {activeTab === "homework" && <HomeworkTab childDetail={childDetail} />}
        {activeTab === "grades" && <GradesTab childDetail={childDetail} />}
        {activeTab === "exams" && <ExamsTab childDetail={childDetail} />}
        {activeTab === "schedule" && <ScheduleTab childDetail={childDetail} />}
      </div>
    </div>
  );
}

function SectionCard({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) {
  return (
    <section className="rounded border border-rule bg-paper-elevated p-4">
      <h3 className="font-serif text-base">{title}</h3>
      <div className="mt-3">{children}</div>
    </section>
  );
}

function OverviewTab({ childDetail }: { childDetail: ChildDetail }) {
  return (
    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
      <SectionCard title="作业摘要">
        <HomeworkSummary detail={childDetail} />
      </SectionCard>
      <SectionCard title="成绩摘要">
        <GradeSummary detail={childDetail} />
      </SectionCard>
      <SectionCard title="今日课表">
        <ScheduleList schedule={childDetail.todaySchedule} />
      </SectionCard>
    </div>
  );
}

function HomeworkTab({ childDetail }: { childDetail: ChildDetail }) {
  return (
    <div className="space-y-4">
      <SectionCard title="作业摘要">
        <HomeworkSummary detail={childDetail} />
      </SectionCard>
      <Link
        href="/parent/homework"
        className="inline-block text-sm font-medium text-accent hover:underline"
      >
        查看全部作业 →
      </Link>
    </div>
  );
}

function GradesTab({ childDetail }: { childDetail: ChildDetail }) {
  return (
    <div className="space-y-4">
      <SectionCard title="成绩摘要">
        <GradeSummary detail={childDetail} />
      </SectionCard>
      <Link
        href="/parent/grades"
        className="inline-block text-sm font-medium text-accent hover:underline"
      >
        查看全部成绩 →
      </Link>
    </div>
  );
}

function ExamsTab({ childDetail }: { childDetail: ChildDetail }) {
  const { examResults } = childDetail;
  return (
    <div className="space-y-4">
      <SectionCard title="考试摘要">
        <div className="grid grid-cols-3 gap-3 text-center">
          <div>
            <div className="font-mono text-xl">{examResults.upcoming}</div>
            <div className="text-xs text-ink-muted">待考</div>
          </div>
          <div>
            <div className="font-mono text-xl">{examResults.completed}</div>
            <div className="text-xs text-ink-muted">已完成</div>
          </div>
          <div>
            <div className="font-mono text-xl">{examResults.avgScore}</div>
            <div className="text-xs text-ink-muted">平均分</div>
          </div>
        </div>
      </SectionCard>
      <Link
        href="/parent/exams"
        className="inline-block text-sm font-medium text-accent hover:underline"
      >
        查看全部考试 →
      </Link>
    </div>
  );
}

function ScheduleTab({ childDetail }: { childDetail: ChildDetail }) {
  const today = new Date().getDay();
  const todayLabel = DAY_LABELS[today] ?? "";

  return (
    <div className="space-y-4">
      <SectionCard title={`今日课表（${todayLabel}）`}>
        <ScheduleList schedule={childDetail.todaySchedule} />
      </SectionCard>
      <SectionCard title="周课表">
        <WeeklySchedule weeklySchedule={childDetail.weeklySchedule} />
      </SectionCard>
    </div>
  );
}

function HomeworkSummary({ detail }: { detail: ChildDetail }) {
  const { homeworkSummary } = detail;
  return (
    <div className="grid grid-cols-2 gap-3 text-sm sm:grid-cols-4">
      <div>
        <div className="font-mono text-lg">{homeworkSummary.pendingCount}</div>
        <div className="text-xs text-ink-muted">待完成</div>
      </div>
      <div>
        <div className="font-mono text-lg">{homeworkSummary.overdueCount}</div>
        <div className="text-xs text-ink-muted">已逾期</div>
      </div>
      <div>
        <div className="font-mono text-lg">{homeworkSummary.submittedCount}</div>
        <div className="text-xs text-ink-muted">已提交</div>
      </div>
      <div>
        <div className="font-mono text-lg">{homeworkSummary.gradedCount}</div>
        <div className="text-xs text-ink-muted">已评分</div>
      </div>
    </div>
  );
}

function GradeSummary({ detail }: { detail: ChildDetail }) {
  const { gradeSummary } = detail;
  const trendLabel =
    gradeSummary.trend === "up"
      ? "↑ 上升"
      : gradeSummary.trend === "down"
        ? "↓ 下降"
        : "→ 平稳";
  const trendTone =
    gradeSummary.trend === "up"
      ? "text-success"
      : gradeSummary.trend === "down"
        ? "text-danger"
        : "text-ink-muted";

  return (
    <div className="grid grid-cols-3 gap-3 text-center">
      <div>
        <div className="font-mono text-lg">{gradeSummary.avgScore}</div>
        <div className="text-xs text-ink-muted">平均分</div>
      </div>
      <div>
        <div className="font-mono text-lg">
          {gradeSummary.classRank}/{gradeSummary.classSize}
        </div>
        <div className="text-xs text-ink-muted">班级排名</div>
      </div>
      <div>
        <div className={cn("font-mono text-lg", trendTone)}>{trendLabel}</div>
        <div className="text-xs text-ink-muted">趋势</div>
      </div>
    </div>
  );
}

function ScheduleList({ schedule }: { schedule: ScheduleItem[] }) {
  if (schedule.length === 0) {
    return (
      <p className="text-sm text-ink-muted">今日无课程</p>
    );
  }
  return (
    <ul className="space-y-2 text-sm">
      {schedule.map((item) => (
        <li
          key={item.id}
          className="flex items-center justify-between border-b border-rule pb-2 last:border-b-0 last:pb-0"
        >
          <div>
            <span className="font-medium">{item.subject}</span>
            <span className="ml-2 text-xs text-ink-muted">
              {item.teacherName} · {item.classroom}
            </span>
          </div>
          <span className="font-mono text-xs text-ink-muted">
            第 {item.period} 节 · {item.startTime}-{item.endTime}
          </span>
        </li>
      ))}
    </ul>
  );
}

function WeeklySchedule({
  weeklySchedule,
}: {
  weeklySchedule: ScheduleItem[];
}) {
  // 按星期分组：1-5（周一到周五）
  const grouped = new Map<number, ScheduleItem[]>();
  for (const item of weeklySchedule) {
    const list = grouped.get(item.dayOfWeek) ?? [];
    list.push(item);
    grouped.set(item.dayOfWeek, list);
  }
  const days = Array.from(grouped.keys()).sort((a, b) => a - b);

  if (days.length === 0) {
    return <p className="text-sm text-ink-muted">暂无周课表</p>;
  }

  return (
    <div className="space-y-3">
      {days.map((day) => {
        const items = grouped.get(day) ?? [];
        return (
          <div key={day}>
            <h4 className="text-xs font-medium text-ink-muted">
              {DAY_LABELS[day] ?? ""}
            </h4>
            <ul className="mt-1 space-y-1 text-sm">
              {items
                .sort((a, b) => a.period - b.period)
                .map((item) => (
                  <li
                    key={item.id}
                    className="flex items-center justify-between"
                  >
                    <span>
                      <span className="font-medium">{item.subject}</span>
                      <span className="ml-2 text-xs text-ink-muted">
                        {item.teacherName}
                      </span>
                    </span>
                    <span className="font-mono text-xs text-ink-muted">
                      第 {item.period} 节 · {item.startTime}-{item.endTime}
                    </span>
                  </li>
                ))}
            </ul>
          </div>
        );
      })}
    </div>
  );
}

export default ChildDetailPanel;
