"use client";

import { useEffect, useRef } from "react";

import KatexRenderer from "@/components/math/KatexRenderer";
import type { VariableTermChoice } from "@/lib/engine/variable-types";

interface VariableChoiceAnswerFormProps {
  choices: [VariableTermChoice[], VariableTermChoice[]];
  selectedChoiceIds: [string | null, string | null];
  activeTermIndex: 0 | 1;
  onSelectChoice: (termIndex: 0 | 1, choiceId: string) => void;
  onSubmit: () => void;
}

export default function VariableChoiceAnswerForm({
  choices,
  selectedChoiceIds,
  activeTermIndex,
  onSelectChoice,
  onSubmit,
}: VariableChoiceAnswerFormProps) {
  const firstChoiceRef = useRef<HTMLButtonElement>(null);
  const submitButtonRef = useRef<HTMLButtonElement>(null);
  const canSubmit = selectedChoiceIds[0] !== null && selectedChoiceIds[1] !== null;
  const activeChoices = choices[activeTermIndex];

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

  useEffect(() => {
    if (canSubmit) {
      submitButtonRef.current?.focus();
    }
  }, [canSubmit]);

  return (
    <div className="rounded-md bg-white p-6 shadow-sm ring-1 ring-slate-200">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <p className="text-sm font-semibold text-slate-500">
            {activeTermIndex === 0 ? "첫째 항" : "둘째 항"}을 고르세요.
          </p>
          <p className="mt-1 text-base text-slate-700">
            괄호를 풀었을 때의 부호를 선택합니다.
          </p>
        </div>
        <div
          className="inline-flex gap-1 rounded-md border border-slate-300 bg-slate-50 p-1"
          role="group"
          aria-label="입력 항 진행 상태"
        >
          {selectedChoiceIds.map((choiceId, index) => {
            const selected = activeTermIndex === index;

            return (
              <span
                key={index}
                className={`inline-flex h-9 min-w-16 items-center justify-center rounded px-3 text-sm font-bold ${
                  selected
                    ? "bg-emerald-700 text-white"
                    : "bg-white text-slate-700"
                }`}
              >
                {choiceId ? `${index + 1}항 완료` : `${index + 1}항`}
              </span>
            );
          })}
        </div>
      </div>

      <div
        className="mt-5 grid gap-3 sm:grid-cols-2"
        role="group"
        aria-label={`${activeTermIndex === 0 ? "첫째 항" : "둘째 항"} 보기 선택`}
      >
        {activeChoices.map((choice, index) => {
          const selected = selectedChoiceIds[activeTermIndex] === choice.id;

          return (
            <button
              key={choice.id}
              ref={index === 0 ? firstChoiceRef : undefined}
              type="button"
              onClick={() => onSelectChoice(activeTermIndex, choice.id)}
              aria-pressed={selected}
              className={`flex h-20 items-center justify-center rounded-md text-3xl font-bold transition focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 ${
                selected
                  ? "bg-emerald-700 text-white"
                  : "bg-slate-50 text-slate-950 ring-1 ring-slate-200 hover:bg-slate-100"
              }`}
            >
              <KatexRenderer latex={choice.latex} />
            </button>
          );
        })}
      </div>

      <button
        ref={submitButtonRef}
        type="button"
        onClick={onSubmit}
        disabled={!canSubmit}
        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 disabled:cursor-not-allowed disabled:bg-slate-300"
      >
        정답 확인
      </button>
    </div>
  );
}
