"use client";

/**
 * ErrorBook — 错题本（批次 A）
 *
 * 数据源：useMyErrorBook + useUpdateErrorBookItem
 * 视图：统计概览 + 学科/状态筛选 + 错题卡片列表 + SM2 复习自评弹窗
 */

import { useMemo, useState } from "react";
import { useMyErrorBook, useUpdateErrorBookItem } from "@/lib/graphql/hooks";
import type { ErrorBookItem, ErrorBookStatus } from "@/lib/graphql/types";

const STATUS_LABELS: Record<ErrorBookStatus, string> = {
  new: "待学习",
  learning: "学习中",
  mastered: "已掌握",
  archived: "已归档",
};

const STATUS_BADGE: Record<ErrorBookStatus, string> = {
  new: "badge-warning",
  learning: "badge-info",
  mastered: "badge-success",
  archived: "badge-info",
};

const REVIEW_OPTIONS = [
  { value: "again", label: "忘记", desc: "1 天后复习" },
  { value: "hard", label: "困难", desc: "3 天后复习" },
  { value: "good", label: "良好", desc: "7 天后复习" },
  { value: "easy", label: "简单", desc: "14 天后复习" },
] as const;

export default function ErrorBookPage(): JSX.Element {
  const { data, fetching, error, reexecute } = useMyErrorBook();
  const [subjectFilter, setSubjectFilter] = useState<string>("all");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [reviewingId, setReviewingId] = useState<string | null>(null);

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

  const subjectOptions = useMemo(() => {
    const set = new Set<string>();
    items.forEach((i) => set.add(i.subject.name));
    return Array.from(set);
  }, [items]);

  const filtered = useMemo(() => {
    return items.filter((i) => {
      if (subjectFilter !== "all" && i.subject.name !== subjectFilter) return false;
      if (statusFilter !== "all" && i.status !== statusFilter) return false;
      return true;
    });
  }, [items, subjectFilter, statusFilter]);

  const reviewingItem = reviewingId ? items.find((i) => i.id === reviewingId) ?? null : null;

  return (
    <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-7xl 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)" }}>
          基于 SM2 间隔重复算法安排复习，标记复习自评以优化记忆曲线。
        </p>
      </header>

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

      {fetching ? (
        <LoadingSkeleton />
      ) : error ? (
        <ErrorState message={error.message} onRetry={() => reexecute()} />
      ) : items.length === 0 ? (
        <EmptyState />
      ) : (
        <>
          {stats && <StatsOverview stats={stats} />}

          <div className="flex flex-wrap items-center gap-3 mb-6">
            <Select
              label="学科"
              value={subjectFilter}
              onChange={setSubjectFilter}
              options={[{ value: "all", label: "全部学科" }, ...subjectOptions.map((s) => ({ value: s, label: s }))]}
            />
            <Select
              label="状态"
              value={statusFilter}
              onChange={setStatusFilter}
              options={[
                { value: "all", label: "全部状态" },
                { value: "new", label: "待学习" },
                { value: "learning", label: "学习中" },
                { value: "mastered", label: "已掌握" },
              ]}
            />
          </div>

          <ul className="space-y-4">
            {filtered.map((item) => (
              <ErrorCard
                key={item.id}
                item={item}
                onReview={() => setReviewingId(item.id)}
              />
            ))}
          </ul>
        </>
      )}

      {reviewingItem && (
        <ReviewDialog
          item={reviewingItem}
          onClose={() => setReviewingId(null)}
        />
      )}
    </div>
  );
}

function StatsOverview({ stats }: { stats: NonNullable<ReturnType<typeof useMyErrorBook>["data"]>["stats"] }): JSX.Element {
  const rate = Math.round(stats.masteredRate * 100);
  return (
    <section className="card-paper p-6 mb-6">
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatBox label="总错题" value={stats.totalCount} />
        <StatBox label="待学习" value={stats.newCount} />
        <StatBox label="学习中" value={stats.learningCount} />
        <StatBox label="已掌握" value={stats.masteredCount} />
      </div>
      <div className="mt-4 flex items-center gap-4 text-sm" style={{ color: "var(--color-ink-muted)" }}>
        <span>待复习：{stats.dueReviewCount} 题</span>
        <span>掌握率：{rate}%</span>
      </div>
    </section>
  );
}

function StatBox({ label, value }: { label: string; value: 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 Select({
  label,
  value,
  onChange,
  options,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  options: Array<{ value: string; label: string }>;
}): JSX.Element {
  return (
    <label className="flex items-center gap-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
      {label}
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="px-3 py-1.5 rounded-sm text-sm"
        style={{
          background: "var(--color-paper)",
          border: "1px solid var(--color-rule)",
          color: "var(--color-ink)",
        }}
      >
        {options.map((o) => (
          <option key={o.value} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
    </label>
  );
}

function ErrorCard({ item, onReview }: { item: ErrorBookItem; onReview: () => void }): JSX.Element {
  const masteryPct = Math.round(item.masteryLevel * 100);
  return (
    <li>
      <article className="card-paper p-5">
        <div className="flex items-start justify-between gap-4 mb-2">
          <div className="flex items-center gap-2">
            <span className="badge badge-info">{item.subject.name}</span>
            <span className={`badge ${STATUS_BADGE[item.status]}`}>
              {STATUS_LABELS[item.status]}
            </span>
          </div>
          <span className="text-xs" style={{ color: "var(--color-ink-muted)" }}>
            掌握度 {masteryPct}%
          </span>
        </div>
        <p className="text-sm font-medium" style={{ color: "var(--color-ink)" }}>
          {item.questionContent}
        </p>
        <p className="mt-1 text-xs" style={{ color: "var(--color-ink-muted)" }}>
          知识点：{item.knowledgePointName} · 已复习 {item.reviewCount} 次
        </p>
        {item.note && (
          <p className="mt-2 text-xs italic" style={{ color: "var(--color-ink-subtle)" }}>
            笔记：{item.note}
          </p>
        )}
        {item.nextReviewAt && (
          <p className="mt-1 text-xs" style={{ color: "var(--color-ink-muted)" }}>
            下次复习：{new Date(item.nextReviewAt).toLocaleDateString("zh-CN")}
          </p>
        )}
        <div className="mt-3 flex gap-2">
          <button type="button" onClick={onReview} className="btn-secondary text-xs">
            复习自评
          </button>
        </div>
      </article>
    </li>
  );
}

function ReviewDialog({ item, onClose }: { item: ErrorBookItem; onClose: () => void }): JSX.Element {
  const { execute, fetching } = useUpdateErrorBookItem();

  const handleReview = (result: "again" | "hard" | "good" | "easy"): void => {
    execute({ id: item.id, reviewResult: result });
    onClose();
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="复习自评"
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      style={{ background: "rgba(0,0,0,0.4)" }}
      onClick={onClose}
    >
      <div
        className="card-paper p-6 max-w-md w-full"
        onClick={(e) => e.stopPropagation()}
      >
        <h3 className="text-lg font-serif mb-2" style={{ color: "var(--color-ink)" }}>
          复习自评
        </h3>
        <p className="text-sm mb-4" style={{ color: "var(--color-ink-muted)" }}>
          {item.questionContent}
        </p>
        <div className="grid grid-cols-2 gap-3">
          {REVIEW_OPTIONS.map((opt) => (
            <button
              key={opt.value}
              type="button"
              disabled={fetching}
              onClick={() => handleReview(opt.value)}
              className="card-paper p-4 text-center transition-opacity hover:opacity-80 disabled:opacity-50"
            >
              <p className="text-base font-serif" style={{ color: "var(--color-ink)" }}>
                {opt.label}
              </p>
              <p className="mt-1 text-xs" style={{ color: "var(--color-ink-muted)" }}>
                {opt.desc}
              </p>
            </button>
          ))}
        </div>
        <button
          type="button"
          onClick={onClose}
          className="mt-4 text-xs"
          style={{ color: "var(--color-ink-muted)" }}
        >
          取消
        </button>
      </div>
    </div>
  );
}

function LoadingSkeleton(): JSX.Element {
  return (
    <div className="card-paper p-6" aria-busy="true" aria-live="polite">
      <div className="grid grid-cols-4 gap-4 mb-6">
        {[0, 1, 2, 3].map((i) => (
          <div key={i} className="h-16 animate-pulse rounded-sm" style={{ background: "var(--color-rule)", opacity: 0.3 }} />
        ))}
      </div>
      <div className="space-y-4">
        {[0, 1, 2].map((i) => (
          <div key={i} className="h-24 animate-pulse rounded-sm" style={{ background: "var(--color-rule)", opacity: 0.3 }} />
        ))}
      </div>
      <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>
  );
}
