"use client";

import { useEffect, useRef } from "react";

import AnswerResultLine from "@/components/game/AnswerResultLine";
import type {
  VariableGradeResult,
  VariableParenthesisProblem,
} from "@/lib/engine/variable-types";
import { formatVariableTermLatex } from "@/lib/engine/variable-parenthesis";

interface VariableFeedbackPanelProps {
  result: VariableGradeResult;
  problem: VariableParenthesisProblem;
  isLastProblem: boolean;
  onNext: () => void;
}

function formatSignedNumber(value: number) {
  return value < 0 ? `(${value})` : `${value}`;
}

export default function VariableFeedbackPanel({
  result,
  problem,
  isLastProblem,
  onNext,
}: VariableFeedbackPanelProps) {
  const nextButtonRef = useRef<HTMLButtonElement>(null);
  const signedTerms = problem.terms.map((term, index) =>
    formatVariableTermLatex({
      ...term,
      coefficient:
        index > 0 && problem.operators[index - 1] === "-"
          ? -term.coefficient
          : term.coefficient,
    }),
  );
  const feedbackItems = signedTerms.map((termLatex, index) => {
    const userAnswer = result.userAnswer[index];
    const correctAnswer = result.correctAnswer[index];

    return {
      formulaLatex: `${formatSignedNumber(problem.multiplier)}\\times ${termLatex}`,
      userAnswerLatex: userAnswer?.latex ?? "?",
      correctAnswerLatex: correctAnswer.latex,
      correct: userAnswer?.coefficient === correctAnswer.coefficient,
    };
  });

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

  return (
    <div
      className={`rounded-md p-6 shadow-sm ring-1 ${
        result.correct
          ? "bg-emerald-50 text-emerald-950 ring-emerald-200"
          : "bg-red-50 text-red-950 ring-red-200"
      }`}
    >
      <p className="text-lg font-bold">
        {result.correct ? "정답입니다." : "오답입니다."}
      </p>
      <ul className="mt-5 space-y-3">
        {feedbackItems.map((item, index) => (
          <AnswerResultLine
            key={index}
            expressionLatex={item.formulaLatex}
            userAnswerLatex={item.userAnswerLatex}
            correctAnswerLatex={item.correctAnswerLatex}
            correct={item.correct}
          />
        ))}
      </ul>
      <button
        ref={nextButtonRef}
        type="button"
        onClick={onNext}
        className="mt-5 inline-flex h-11 items-center justify-center rounded-md bg-slate-950 px-5 text-base font-semibold text-white transition hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-slate-500 focus:ring-offset-2"
      >
        {isLastProblem ? "결과 보기" : "다음 문제"}
      </button>
    </div>
  );
}
