"use client";

/**
 * CoursePlans — 课程计划列表（批次 A）
 *
 * 数据源：useMyCoursePlans
 * 视图：课程计划列表（进度条 + 状态 + 周课时）
 */

import Link from "next/link";
import { useMyCoursePlans } from "@/lib/graphql/hooks";
import type { CoursePlanStatus, CoursePlanSemester } from "@/lib/graphql/types";

const STATUS_LABELS: Record<CoursePlanStatus, string> = {
  planning: "规划中",
  active: "进行中",
  completed: "已完成",
  paused: "已暂停",
};

const STATUS_BADGE: Record<CoursePlanStatus, string> = {
  planning: "badge-warning",
  active: "badge-success",
  completed: "badge-info",
  paused: "badge-warning",
};

const SEMESTER_LABELS: Record<CoursePlanSemester, string> = {
  "1": "上学期",
  "2": "下学期",
};

export default function CoursePlansPage(): JSX.Element {
  const { data, fetching, error, reexecute } = useMyCoursePlans();
  const plans = data ?? [];

  return (
    <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-5xl mx-auto">
      <header className="mb-6">
        <p className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
          教学进度
        </p>
        <h1 className="mt-2 text-3xl lg:text-4xl font-serif" style={{ color: "var(--color-ink)" }}>
          课程计划
        </h1>
        <p className="mt-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
          查看各学科本学期教学计划与完成进度。
        </p>
      </header>

      <div className="rule-thin mb-8" />

      {fetching ? (
        <LoadingSkeleton />
      ) : error ? (
        <ErrorState message={error.message} onRetry={() => reexecute()} />
      ) : plans.length === 0 ? (
        <EmptyState />
      ) : (
        <ul className="space-y-4">
          {plans.map((p) => {
            const progress = p.totalHours > 0 ? (p.completedHours / p.totalHours) * 100 : 0;
            return (
              <li key={p.id}>
                <Link href={`/course-plans/${p.id}`} className="block">
                  <article className="card-paper p-5 transition-opacity hover:opacity-80">
                    <div className="flex items-start justify-between gap-4 mb-2">
                      <div className="flex items-center gap-2">
                        {p.subjectName && <span className="badge badge-info">{p.subjectName}</span>}
                        <span className={`badge ${STATUS_BADGE[p.status]}`}>
                          {STATUS_LABELS[p.status]}
                        </span>
                        <span className="text-xs" style={{ color: "var(--color-ink-muted)" }}>
                          {SEMESTER_LABELS[p.semester]}
                        </span>
                      </div>
                      <span className="text-xs" style={{ color: "var(--color-ink-muted)" }}>
                        {p.completedHours}/{p.totalHours} 课时
                      </span>
                    </div>
                    <p className="text-sm font-medium" style={{ color: "var(--color-ink)" }}>
                      {p.className ?? "—"} · {p.teacherName ?? "—"}
                    </p>
                    {p.syllabus && (
                      <p className="mt-1 text-xs text-truncate" style={{ color: "var(--color-ink-muted)" }}>
                        {p.syllabus}
                      </p>
                    )}
                    <div className="mt-3 flex items-center gap-3">
                      <div className="flex-1 h-1.5 rounded-sm overflow-hidden" style={{ background: "var(--color-rule)" }}>
                        <div
                          className="h-full"
                          style={{ width: `${Math.min(progress, 100)}%`, background: "var(--color-accent)" }}
                        />
                      </div>
                      <span className="text-xs flex-shrink-0" style={{ color: "var(--color-ink-muted)" }}>
                        {Math.round(progress)}%
                      </span>
                    </div>
                  </article>
                </Link>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}

function LoadingSkeleton(): JSX.Element {
  return (
    <div className="space-y-4" aria-busy="true" aria-live="polite">
      {[0, 1, 2].map((i) => (
        <div
          key={i}
          className="h-24 animate-pulse rounded-sm"
          style={{ background: "var(--color-rule)", opacity: 0.3 }}
        />
      ))}
      <span className="sr-only">正在加载课程计划...</span>
    </div>
  );
}

function ErrorState({ message, onRetry }: { message: string; onRetry: () => void }): JSX.Element {
  return (
    <div role="alert" className="card-paper p-8 text-center" style={{ borderColor: "var(--color-danger)" }}>
      <p className="text-base font-serif" style={{ color: "var(--color-danger)" }}>
        课程计划加载失败
      </p>
      <p className="mt-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
        {message}
      </p>
      <button type="button" onClick={onRetry} className="mt-4 btn-secondary text-xs">
        重新加载
      </button>
    </div>
  );
}

function EmptyState(): JSX.Element {
  return (
    <div className="card-paper p-8 text-center">
      <p className="text-4xl font-serif" style={{ color: "var(--color-ink-subtle)" }} aria-hidden="true">
        ◇
      </p>
      <p className="mt-4 text-base font-serif" style={{ color: "var(--color-ink)" }}>
        暂无课程计划
      </p>
    </div>
  );
}
