"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 {
  DistributedVariableTerm,
  VariableGradeResult,
  VariableParenthesisProblem,
} from "@/lib/engine/variable-types";
import { formatVariableExpressionLatex } from "@/lib/engine/variable-parenthesis";

interface VariableScoreSummaryProps {
  correctCount: number;
  totalCount: number;
  problems: VariableParenthesisProblem[];
  results: (VariableGradeResult | null)[];
  onRestart: () => void;
}

function renderTermPair(
  terms: (DistributedVariableTerm | null)[],
  comparisonTerms: (DistributedVariableTerm | null)[],
  mode: "user" | "correct",
) {
  return (
    <span className="inline-flex flex-wrap items-center gap-x-2 gap-y-1">
      {terms.map((term, index) => {
        if (!term) {
          return (
            <span key={index} className="text-red-700">
              ?
            </span>
          );
        }

        const correct = term.coefficient === comparisonTerms[index]?.coefficient;
        const className =
          mode === "user"
            ? correct
              ? undefined
              : "text-red-700"
            : correct
              ? undefined
              : "font-bold text-blue-700";
        const operator = term.coefficient < 0 ? "-" : "+";
        const displayLatex =
          index === 0 ? term.latex : `${operator} ${term.latex.replace(/^-/, "")}`;

        return (
          <span key={index} className={className}>
            <KatexRenderer latex={displayLatex} output="mathml" />
          </span>
        );
      })}
    </span>
  );
}

export default function VariableScoreSummary({
  correctCount,
  totalCount,
  problems,
  results,
  onRestart,
}: VariableScoreSummaryProps) {
  const restartButtonRef = useRef<HTMLButtonElement>(null);
  const solvedItems = problems
    .map((problem, index) => ({
      problem,
      result: results[index],
    }))
    .filter(
      (
        item,
      ): item is {
        problem: VariableParenthesisProblem;
        result: VariableGradeResult;
      } => 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) => (
            <AnswerResultLine
              key={problem.key}
              expressionLatex={problem.latexBefore}
              userAnswerLatex={formatVariableExpressionLatex([
                ...result.correctAnswer.map(
                  (term, termIndex) => result.userAnswer[termIndex] ?? term,
                ),
              ])}
              correctAnswerLatex={problem.latexAfter}
              correct={result.correct}
              userAnswerContent={renderTermPair(
                result.userAnswer,
                result.correctAnswer,
                "user",
              )}
              correctAnswerContent={renderTermPair(
                result.correctAnswer,
                result.userAnswer,
                "correct",
              )}
              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>
  );
}
