"use client";

import Link from "next/link";
import { useEffect, useState } from "react";

import {
  formatDuration,
  formatTakenAt,
  loadQuizHistory,
  type QuizResult,
} from "./quiz-storage";

export function RecentHistoryPanel({ limit = 5 }: { limit?: number }) {
  const [history, setHistory] = useState<QuizResult[] | null>(null);

  useEffect(() => {
    setHistory(loadQuizHistory());
  }, []);

  if (history === null) {
    return (
      <div className="rounded-xl border border-[var(--color-line)] bg-[var(--color-mist)]/30 p-6">
        <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
          Recent attempts
        </div>
        <p className="mt-3 text-[14px] text-[var(--color-slate)]">
          Loading history…
        </p>
      </div>
    );
  }

  const shown = history.slice(0, limit);

  return (
    <div className="rounded-xl border border-[var(--color-line)] bg-[var(--color-mist)]/30 p-6">
      <div className="flex items-center justify-between">
        <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
          Recent attempts
        </div>
        {history.length > 0 && (
          <Link
            href="/products/orthoprep/quiz/history"
            className="text-[12px] font-semibold text-[var(--color-blue)] hover:underline"
          >
            View all →
          </Link>
        )}
      </div>

      {shown.length === 0 ? (
        <p className="mt-4 text-[14px] leading-relaxed text-[var(--color-slate)]">
          No attempts yet. Pick a mode to start your first quiz — your results
          save locally in this browser.
        </p>
      ) : (
        <ul className="mt-4 space-y-3">
          {shown.map((r) => {
            const pct = Math.round((r.correctCount / r.questionCount) * 100);
            return (
              <li
                key={r.id}
                className="rounded-lg border border-[var(--color-line)] bg-white p-4"
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <div className="text-[13px] font-semibold text-[var(--color-ink)] truncate">
                      {r.mode === "part" && r.partTitle
                        ? r.partTitle
                        : `Random · ${r.questionCount}`}
                    </div>
                    <div className="mt-1 text-[11px] text-[var(--color-slate)]">
                      {formatTakenAt(r.takenAt)} ·{" "}
                      {formatDuration(r.durationMs)}
                    </div>
                  </div>
                  <div className="shrink-0 text-right">
                    <div className="font-display text-[18px] font-bold leading-none text-[var(--color-blue)]">
                      {pct}%
                    </div>
                    <div className="mt-1 text-[11px] text-[var(--color-slate)]">
                      {r.correctCount}/{r.questionCount}
                    </div>
                  </div>
                </div>
                <div className="mt-3 h-1.5 overflow-hidden rounded-full bg-[var(--color-mist)]">
                  <div
                    className="h-full bg-[var(--color-blue)]"
                    style={{ width: `${pct}%` }}
                  />
                </div>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}
