"use client";

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

import AnswerResultLine from "@/components/game/AnswerResultLine";
import KatexRenderer from "@/components/math/KatexRenderer";
import type { GradeResult, ParenthesisSignProblem } from "@/lib/engine/types";

interface ScoreSummaryProps {
  correctCount: number;
  totalCount: number;
  problems: ParenthesisSignProblem[];
  results: (GradeResult | null)[];
  onRestart: () => void;
}

function formatAnswerLatex(terms: number[]) {
  return terms
    .map((term, index) => {
      if (index === 0) return `${term}`;

      const operator = term < 0 ? "-" : "+";
      return `${operator} ${Math.abs(term)}`;
    })
    .join(" ");
}

function renderUserAnswerPair(result: GradeResult) {
  return (
    <span className="inline-flex flex-wrap items-center gap-x-2 gap-y-1">
      {result.userAnswer.map((term, index) => {
        const operator = term < 0 ? "-" : "+";
        const correct = term === result.correctAnswer[index];
        const displayLatex =
          index === 0 ? `${term}` : `${operator} ${Math.abs(term)}`;

        return (
          <span key={index} className={correct ? undefined : "text-red-700"}>
            <KatexRenderer latex={displayLatex} output="mathml" />
          </span>
        );
      })}
    </span>
  );
}

function renderCorrectAnswerPair(result: GradeResult) {
  return (
    <span className="inline-flex flex-wrap items-center gap-x-2 gap-y-1">
      {result.correctAnswer.map((term, index) => {
        const operator = term < 0 ? "-" : "+";
        const correct = result.userAnswer[index] === term;
        const displayLatex =
          index === 0 ? `${term}` : `${operator} ${Math.abs(term)}`;

        return (
          <span
            key={index}
            className={correct ? undefined : "font-bold text-blue-700"}
          >
            <KatexRenderer latex={displayLatex} output="mathml" />
          </span>
        );
      })}
    </span>
  );
}

export default function ScoreSummary({
  correctCount,
  totalCount,
  problems,
  results,
  onRestart,
}: ScoreSummaryProps) {
  const restartButtonRef = useRef<HTMLButtonElement>(null);
  const solvedItems = problems
    .map((problem, index) => ({
      problem,
      result: results[index],
    }))
    .filter(
      (item): item is { problem: ParenthesisSignProblem; result: GradeResult } =>
        item.result !== null,
    );

  useEffect(() => {
    restartButtonRef.current?.focus();
  }, []);

  return (
    <main className="flex min-h-screen items-center bg-slate-50 px-6 py-12 text-slate-950">
      <section className="mx-auto flex w-full max-w-3xl flex-col gap-8">
        <div className="space-y-3">
          <p className="text-sm font-semibold text-emerald-700">
            괄호 음수 분배
          </p>
          <h1 className="text-4xl font-bold tracking-normal sm:text-5xl">
            풀이 결과
          </h1>
          <p className="text-xl font-semibold text-slate-800">
            {correctCount} / {totalCount} 정답
          </p>
        </div>

        <ol className="space-y-3">
          {solvedItems.map(({ problem, result }, index) => {
            const userAnswerLatex = formatAnswerLatex(result.userAnswer);

            return (
              <AnswerResultLine
                key={problem.key}
                expressionLatex={problem.latexBefore}
                userAnswerLatex={userAnswerLatex}
                correctAnswerLatex={problem.latexAfter}
                correct={result.correct}
                userAnswerContent={renderUserAnswerPair(result)}
                correctAnswerContent={renderCorrectAnswerPair(result)}
                prefix={
                  <span className="mr-1 text-sm font-bold text-slate-500">
                    {index + 1}.
                  </span>
                }
              />
            );
          })}
        </ol>

        <div className="flex flex-wrap gap-3">
          <button
            ref={restartButtonRef}
            type="button"
            onClick={onRestart}
            className="inline-flex h-12 items-center justify-center rounded-md bg-emerald-700 px-6 text-base font-semibold text-white transition hover:bg-emerald-800 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2"
          >
            다시 시작
          </button>
          <Link
            href="/"
            className="inline-flex h-12 items-center justify-center rounded-md border border-slate-300 px-6 text-base font-semibold text-slate-800 transition hover:bg-white focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2"
          >
            처음으로
          </Link>
        </div>
      </section>
    </main>
  );
}
