"use client";

/**
 * Practice — 自适应练习（批次 A）
 *
 * 数据源：useMyPracticeSessions + useStartPracticeSession
 * 视图：练习统计 + 会话列表 + 启动新练习
 */

import { useRouter } from "next/navigation";
import {
  useMyPracticeSessions,
  useStartPracticeSession,
} from "@/lib/graphql/hooks";
import type { PracticeStatus, PracticeType } from "@/lib/graphql/types";

const PRACTICE_TYPE_LABELS: Record<PracticeType, string> = {
  error_variant: "错题变式",
  knowledge_point: "知识点练习",
  weak_chapter: "薄弱章节",
  ai_recommended: "AI 推荐",
};

const PRACTICE_STATUS_LABELS: Record<PracticeStatus, string> = {
  in_progress: "进行中",
  completed: "已完成",
  abandoned: "已放弃",
};

const PRACTICE_STATUS_BADGE: Record<PracticeStatus, string> = {
  in_progress: "badge-info",
  completed: "badge-success",
  abandoned: "badge-warning",
};

export default function PracticePage(): JSX.Element {
  const router = useRouter();
  const { data, fetching, error, reexecute } = useMyPracticeSessions();
  const { execute: startExecute, fetching: startFetching } = useStartPracticeSession();

  const sessions = data?.sessions ?? [];
  const stats = data?.stats;

  const handleStart = (practiceType: PracticeType): void => {
    startExecute({ practiceType, questionCount: 10 });
    // 导航到练习会话页（mock 模式下 sessionId 为临时值）
    router.push("/practice/session-active");
  };

  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" />

      <section className="mb-8">
        <h2 className="text-base font-serif mb-4" style={{ color: "var(--color-ink)" }}>
          开始新练习
        </h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {(Object.keys(PRACTICE_TYPE_LABELS) as PracticeType[]).map((pt) => (
            <button
              key={pt}
              type="button"
              onClick={() => handleStart(pt)}
              disabled={startFetching}
              className="card-paper p-4 text-center transition-opacity hover:opacity-80 disabled:opacity-50"
            >
              <p className="text-sm font-serif" style={{ color: "var(--color-ink)" }}>
                {PRACTICE_TYPE_LABELS[pt]}
              </p>
              <p className="mt-1 text-xs" style={{ color: "var(--color-ink-muted)" }}>
                10 题
              </p>
            </button>
          ))}
        </div>
      </section>

      {stats && (
        <section className="card-paper p-6 mb-6">
          <h2 className="text-base font-serif mb-4" style={{ color: "var(--color-ink)" }}>
            练习统计
          </h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <StatBox label="总会话数" value={stats.totalSessions} />
            <StatBox label="已完成" value={stats.completedSessions} />
            <StatBox label="答题总数" value={stats.totalQuestionsAnswered} />
            <StatBox label="总体正确率" value={`${Math.round(stats.overallAccuracy * 100)}%`} />
          </div>
        </section>
      )}

      {fetching ? (
        <LoadingSkeleton />
      ) : error ? (
        <ErrorState message={error.message} onRetry={() => reexecute()} />
      ) : sessions.length === 0 ? (
        <EmptyState />
      ) : (
        <section>
          <h2 className="text-base font-serif mb-4" style={{ color: "var(--color-ink)" }}>
            练习记录
          </h2>
          <ul className="space-y-3">
            {sessions.map((s) => (
              <li key={s.id}>
                <article className="card-paper p-4">
                  <div className="flex items-start justify-between gap-4 mb-2">
                    <div className="flex items-center gap-2">
                      <span className="badge badge-info">
                        {PRACTICE_TYPE_LABELS[s.practiceType]}
                      </span>
                      <span className={`badge ${PRACTICE_STATUS_BADGE[s.status]}`}>
                        {PRACTICE_STATUS_LABELS[s.status]}
                      </span>
                    </div>
                    <span className="text-sm font-serif" style={{ color: "var(--color-ink)" }}>
                      {Math.round(s.accuracy * 100)}%
                    </span>
                  </div>
                  <p className="text-xs" style={{ color: "var(--color-ink-muted)" }}>
                    {s.correctCount}/{s.answeredQuestions} 正确 · 共 {s.totalQuestions} 题
                  </p>
                  <p className="mt-1 text-xs" style={{ color: "var(--color-ink-subtle)" }}>
                    开始：{new Date(s.startedAt).toLocaleString("zh-CN")}
                    {s.completedAt && ` · 完成：${new Date(s.completedAt).toLocaleString("zh-CN")}`}
                  </p>
                </article>
              </li>
            ))}
          </ul>
        </section>
      )}
    </div>
  );
}

function StatBox({ label, value }: { label: string; value: string | number }): JSX.Element {
  return (
    <div>
      <p className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
        {label}
      </p>
      <p className="mt-1 text-2xl font-serif" style={{ color: "var(--color-ink)" }}>
        {value}
      </p>
    </div>
  );
}

function LoadingSkeleton(): JSX.Element {
  return (
    <div className="space-y-3" aria-busy="true" aria-live="polite">
      {[0, 1, 2].map((i) => (
        <div
          key={i}
          className="h-20 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>
      <p className="mt-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
        选择上方练习类型开始第一次练习。
      </p>
    </div>
  );
}
