"use client";

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

import { Container } from "@/components/Container";
import {
  formatDuration,
  getCategoryStats,
  getOverallStats,
  type CategoryStat,
} from "@/components/orthoprep/quiz-storage";

type Overall = ReturnType<typeof getOverallStats>;

export default function StatsClient() {
  const [mounted, setMounted] = useState(false);
  const [overall, setOverall] = useState<Overall>({
    sessions: 0,
    questions: 0,
    correct: 0,
    accuracy: 0,
    totalDurationMs: 0,
  });
  const [categories, setCategories] = useState<CategoryStat[]>([]);

  useEffect(() => {
    setOverall(getOverallStats());
    setCategories(getCategoryStats());
    setMounted(true);
  }, []);

  const accuracyPct = Math.round(overall.accuracy * 100);

  return (
    <section className="bg-gradient-to-b from-white via-white to-[var(--color-mist)]/40 pt-10 pb-10 md:pt-14 md:pb-14">
      <Container>
        <div className="mx-auto max-w-4xl">
          <div className="mb-8 flex flex-wrap items-center justify-between gap-3 text-[13px]">
            <Link
              href="/products/orthoprep/quiz"
              className="font-semibold text-[var(--color-blue)] underline underline-offset-2"
            >
              &larr; Quiz hub
            </Link>
            <span className="rounded-full border border-[var(--color-line)] bg-white px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
              Your stats
            </span>
          </div>

          <header className="mb-10">
            <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
              Progress tracker
            </div>
            <h1 className="mt-2 font-display text-[36px] font-extrabold leading-[1.05] tracking-[-0.02em] text-[var(--color-ink)] md:text-[44px]">
              Where are you strong? Where to drill next?
            </h1>
            <p className="mt-4 max-w-2xl text-[16px] leading-relaxed text-[var(--color-slate)]">
              Every quiz session you finish on this device is counted here.
              Stats are stored locally in your browser&mdash;clearing history
              from the quiz hub will reset them.
            </p>
          </header>

          {mounted && overall.sessions === 0 ? (
            <div className="rounded-xl border border-[var(--color-line)] bg-white p-10 text-center shadow-[0_1px_0_var(--color-line)]">
              <h2 className="font-display text-[22px] font-bold text-[var(--color-ink)]">
                No sessions yet
              </h2>
              <p className="mt-3 text-[14px] text-[var(--color-slate)]">
                Take a quiz and come back to see how you&rsquo;re doing.
              </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)]"
              >
                Go to quiz hub
              </Link>
            </div>
          ) : (
            <>
              <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
                <StatCard label="Sessions" value={overall.sessions} />
                <StatCard label="Questions" value={overall.questions} />
                <StatCard
                  label="Accuracy"
                  value={`${accuracyPct}%`}
                  tone={
                    accuracyPct >= 70
                      ? "good"
                      : accuracyPct >= 50
                        ? "mid"
                        : "bad"
                  }
                />
                <StatCard
                  label="Total time"
                  value={formatDuration(overall.totalDurationMs)}
                />
              </div>

              <div className="mt-12">
                <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                  By category
                </div>
                <h2 className="mt-2 font-display text-[24px] font-bold tracking-tight text-[var(--color-ink)]">
                  Accuracy per FRCS part
                </h2>

                <div className="mt-6 space-y-4">
                  {categories.map((cat, i) => {
                    const pct = Math.round(cat.accuracy * 100);
                    const tone =
                      pct >= 70
                        ? "bg-emerald-500"
                        : pct >= 50
                          ? "bg-[var(--color-blue)]"
                          : "bg-red-400";
                    return (
                      <div
                        key={cat.partSlug}
                        className="rounded-xl border border-[var(--color-line)] bg-white p-5 shadow-[0_1px_0_var(--color-line)]"
                      >
                        <div className="flex flex-wrap items-baseline justify-between gap-2">
                          <div className="font-display text-[16px] font-bold text-[var(--color-ink)]">
                            {cat.partTitle}
                          </div>
                          <div className="text-[13px] font-semibold text-[var(--color-slate)]">
                            {cat.correct} / {cat.attempted}
                            <span className="ml-2 text-[var(--color-ink)]">
                              {pct}%
                            </span>
                          </div>
                        </div>
                        <div className="mt-3 h-2.5 overflow-hidden rounded-full bg-[var(--color-mist)]">
                          <motion.div
                            className={`h-full ${tone}`}
                            initial={{ width: 0 }}
                            animate={{ width: `${pct}%` }}
                            transition={{
                              duration: 0.8,
                              ease: "easeOut",
                              delay: 0.08 * i,
                            }}
                          />
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              <div className="mt-12 flex flex-wrap items-center gap-3">
                <Link
                  href="/products/orthoprep/quiz/review"
                  className="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)]"
                >
                  Drill wrong answers
                </Link>
                <Link
                  href="/products/orthoprep/quiz/history"
                  className="inline-flex items-center gap-2 rounded-lg border border-[var(--color-line)] bg-white px-5 py-2.5 text-[14px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                >
                  View full history
                </Link>
              </div>
            </>
          )}
        </div>
      </Container>
    </section>
  );
}

function StatCard({
  label,
  value,
  tone,
}: {
  label: string;
  value: string | number;
  tone?: "good" | "mid" | "bad";
}) {
  const valueClass =
    tone === "good"
      ? "text-emerald-700"
      : tone === "bad"
        ? "text-red-700"
        : tone === "mid"
          ? "text-[var(--color-blue)]"
          : "text-[var(--color-ink)]";
  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-1 font-display text-[26px] font-extrabold leading-none ${valueClass}`}
      >
        {value}
      </div>
    </div>
  );
}
