"use client";

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

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

export function HistoryView() {
  const [history, setHistory] = useState<QuizResult[] | null>(null);

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

  const stats = useMemo(() => {
    if (!history || history.length === 0) {
      return {
        total: 0,
        avgPct: 0,
        bestPct: 0,
        totalQuestions: 0,
        totalCorrect: 0,
        totalDurationMs: 0,
      };
    }
    const totalQuestions = history.reduce(
      (s, r) => s + r.questionCount,
      0,
    );
    const totalCorrect = history.reduce((s, r) => s + r.correctCount, 0);
    const totalDurationMs = history.reduce((s, r) => s + r.durationMs, 0);
    const pcts = history.map(
      (r) => (r.correctCount / r.questionCount) * 100,
    );
    const avgPct = pcts.reduce((s, p) => s + p, 0) / pcts.length;
    const bestPct = Math.max(...pcts);
    return {
      total: history.length,
      avgPct: Math.round(avgPct),
      bestPct: Math.round(bestPct),
      totalQuestions,
      totalCorrect,
      totalDurationMs,
    };
  }, [history]);

  if (history === null) {
    return (
      <p className="text-[14px] text-[var(--color-slate)]">
        Loading history…
      </p>
    );
  }

  if (history.length === 0) {
    return (
      <div className="rounded-xl border border-dashed border-[var(--color-line)] bg-[var(--color-mist)]/30 p-10 text-center">
        <p className="font-display text-[20px] font-bold text-[var(--color-ink)]">
          No attempts yet
        </p>
        <p className="mt-2 text-[14px] leading-relaxed text-[var(--color-slate)]">
          Take a quiz and your results will appear here — saved locally in
          your browser.
        </p>
        <Link
          href="/products/orthoprep/quiz"
          className="mt-6 inline-flex items-center gap-2 rounded-lg bg-[var(--color-blue)] px-5 py-2.5 text-[14px] font-semibold text-white hover:bg-[var(--color-blue-deep)]"
        >
          Start a quiz →
        </Link>
      </div>
    );
  }

  // Chronological ascending for the bar chart (oldest → newest).
  const chronological = [...history].slice().reverse();
  const maxBars = 20;
  const bars = chronological.slice(-maxBars);

  return (
    <div>
      {/* Summary stats */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard label="Attempts" value={stats.total} />
        <StatCard label="Average score" value={`${stats.avgPct}%`} />
        <StatCard label="Best score" value={`${stats.bestPct}%`} />
        <StatCard
          label="Total time"
          value={formatDuration(stats.totalDurationMs)}
        />
      </div>

      {/* Score trend */}
      <section className="mt-10 rounded-xl border border-[var(--color-line)] bg-white p-6">
        <div className="flex items-center justify-between">
          <div>
            <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
              Score trend
            </div>
            <h2 className="mt-1 font-display text-[20px] font-bold tracking-tight text-[var(--color-ink)]">
              Last {bars.length} attempts
            </h2>
          </div>
          <div className="text-[11px] text-[var(--color-slate)]">
            {stats.totalCorrect}/{stats.totalQuestions} total correct
          </div>
        </div>

        <div className="mt-6 flex items-end gap-1.5 h-40">
          {bars.map((r) => {
            const pct = Math.round((r.correctCount / r.questionCount) * 100);
            const tone =
              pct >= 80
                ? "bg-emerald-500"
                : pct >= 60
                  ? "bg-[var(--color-blue)]"
                  : pct >= 40
                    ? "bg-amber-400"
                    : "bg-red-400";
            return (
              <div
                key={r.id}
                className="group relative flex h-full flex-1 flex-col justify-end"
                title={`${pct}% on ${formatTakenAt(r.takenAt)}`}
              >
                <div
                  className={`w-full rounded-t ${tone} transition-opacity group-hover:opacity-80`}
                  style={{ height: `${Math.max(4, pct)}%` }}
                />
              </div>
            );
          })}
        </div>
        <div className="mt-2 flex justify-between text-[10px] text-[var(--color-slate)]">
          <span>Oldest</span>
          <span>Newest</span>
        </div>
      </section>

      {/* Full list */}
      <section className="mt-10">
        <div className="flex items-center justify-between">
          <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
            All attempts
          </div>
          <button
            type="button"
            onClick={() => {
              if (
                typeof window !== "undefined" &&
                window.confirm(
                  "Clear all locally stored quiz history? This cannot be undone.",
                )
              ) {
                clearQuizHistory();
                setHistory([]);
              }
            }}
            className="text-[12px] font-semibold text-[var(--color-slate)] hover:text-red-600"
          >
            Clear history
          </button>
        </div>
        <ul className="mt-4 divide-y divide-[var(--color-line)] rounded-xl border border-[var(--color-line)] bg-white">
          {history.map((r) => {
            const pct = Math.round((r.correctCount / r.questionCount) * 100);
            return (
              <li
                key={r.id}
                className="flex flex-wrap items-center gap-4 p-5"
              >
                <div className="min-w-0 flex-1">
                  <div className="font-display text-[15px] font-bold text-[var(--color-ink)] truncate">
                    {r.mode === "part" && r.partTitle
                      ? r.partTitle
                      : `Random · ${r.questionCount} questions`}
                  </div>
                  <div className="mt-0.5 text-[12px] text-[var(--color-slate)]">
                    {formatTakenAt(r.takenAt)} ·{" "}
                    {formatDuration(r.durationMs)}
                  </div>
                </div>
                <div className="flex w-48 items-center gap-3">
                  <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--color-mist)]">
                    <div
                      className="h-full bg-[var(--color-blue)]"
                      style={{ width: `${pct}%` }}
                    />
                  </div>
                  <div className="w-14 text-right font-display text-[15px] font-bold text-[var(--color-ink)]">
                    {pct}%
                  </div>
                </div>
              </li>
            );
          })}
        </ul>
      </section>
    </div>
  );
}

function StatCard({
  label,
  value,
}: {
  label: string;
  value: string | number;
}) {
  return (
    <div className="rounded-xl border border-[var(--color-line)] bg-white p-5">
      <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
        {label}
      </div>
      <div className="mt-2 font-display text-[28px] font-extrabold leading-none text-[var(--color-blue)]">
        {value}
      </div>
    </div>
  );
}
