import { AppIcon } from "./PixelIcons";
import { Tag } from "./ui";
import { resolveMistakeApi } from "../lib/skillProgress";
import {
  cleanPrincipleTitle,
  countOpenMistakes,
  type DrillMistakeBook as MistakeBook,
  type SkillTreeNode,
} from "../lib/skillTree";

function formatWhen(iso: string) {
  try {
    const d = new Date(iso);
    return d.toLocaleString("zh-TW", { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
  } catch {
    return iso;
  }
}

export default function SkillMistakeBook({
  book,
  nodeById,
  onBookChange,
  onRetry,
  onViewRecords,
}: {
  book: MistakeBook;
  nodeById: Map<string, SkillTreeNode>;
  onBookChange: (book: MistakeBook) => void;
  onRetry: (node: SkillTreeNode) => void;
  onViewRecords?: (node: SkillTreeNode) => void;
}) {
  const open = book.filter((m) => !m.resolved);
  const openCount = countOpenMistakes(book);

  if (!open.length) return null;

  return (
    <section className="skill-mistake-book card pad-sm" aria-label="錯題本">
      <div className="skill-mistake-head">
        <AppIcon name="folder" size={22} framed variant="hero" />
        <div>
          <strong>錯題本</strong>
          <p className="small muted">
            只顯示尚未解決的錯題。試煉未達 95 分、有致命錯誤，或第 1 關答錯會收錄；完整歷史請看各卡片的答題紀錄。
          </p>
        </div>
        {openCount ? <Tag tone="gold">{openCount} 待補</Tag> : <Tag>全部掌握</Tag>}
      </div>

      <ul className="skill-mistake-list">
        {open.map((m) => {
          const node = nodeById.get(m.principleId);
          const title = cleanPrincipleTitle(m.principleTitle);
          return (
            <li className="skill-mistake-item" key={m.id}>
              <div className="skill-mistake-main">
                <div className="skill-mistake-title">{title}</div>
                <div className="skill-mistake-meta small muted">
                  {formatWhen(m.attemptedAt)} · 得分 {m.score}
                  {m.step1Wrong ? " · 第1關答錯" : ""}
                  {m.fatalErrors.length ? " · 致命錯誤" : ""}
                </div>
                {m.feedback ? (
                  <div className="skill-mistake-coach small">
                    <span className="skill-mistake-coach-k">教練當時說：</span>
                    {m.feedback}
                  </div>
                ) : null}
                {m.weakPoints.length ? (
                  <div className="skill-mistake-weak small">
                    待加強：{m.weakPoints.slice(0, 3).join("、")}
                  </div>
                ) : null}
              </div>
                <div className="skill-mistake-actions">
                  {node && onViewRecords ? (
                    <button type="button" className="btn-ghost sm" onClick={() => onViewRecords(node)}>
                      看紀錄
                    </button>
                  ) : null}
                  {node ? (
                    <button type="button" className="btn-primary sm" onClick={() => onRetry(node)}>
                      重練
                    </button>
                  ) : null}
                <button
                  type="button"
                  className="btn-ghost sm"
                  onClick={() => {
                    void resolveMistakeApi(m.id).then(onBookChange);
                  }}
                >
                  標記已掌握
                </button>
              </div>
            </li>
          );
        })}
      </ul>

    </section>
  );
}