"use client";

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

import KatexRenderer from "@/components/math/KatexRenderer";
import { useGameStore } from "@/store/gameStore";

function parseAnswer(value: string) {
  if (value.trim() === "") return null;

  const parsed = Number.parseInt(value, 10);
  return Number.isNaN(parsed) ? null : parsed;
}

export default function PlayClient() {
  const session = useGameStore((state) => state.session);
  const initSession = useGameStore((state) => state.initSession);
  const submitAnswer = useGameStore((state) => state.submitAnswer);
  const nextProblem = useGameStore((state) => state.nextProblem);
  const resetSession = useGameStore((state) => state.resetSession);

  const [answerA, setAnswerA] = useState("");
  const [answerB, setAnswerB] = useState("");
  const [inputError, setInputError] = useState("");

  const currentProblem = session?.problems[session.currentIndex] ?? null;
  const currentResult = session?.results[session.currentIndex] ?? null;
  const isComplete = Boolean(
    session && session.currentIndex >= session.problems.length,
  );
  const correctCount =
    session?.results.filter((result) => result?.correct).length ?? 0;
  const totalCount = session?.problems.length ?? 0;

  useEffect(() => {
    if (session === null) {
      initSession();
    }
  }, [initSession, session]);

  useEffect(() => {
    setAnswerA("");
    setAnswerB("");
    setInputError("");
  }, [currentProblem?.key]);

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();

    if (currentResult || !currentProblem) return;

    const parsedA = parseAnswer(answerA);
    const parsedB = parseAnswer(answerB);

    if (parsedA === null || parsedB === null) {
      setInputError("두 칸 모두 정수로 입력하세요.");
      return;
    }

    setInputError("");
    submitAnswer({ a: parsedA, b: parsedB });
  }

  if (!session) {
    return (
      <main className="flex min-h-screen items-center bg-slate-50 px-6 py-12 text-slate-950">
        <section className="mx-auto w-full max-w-3xl">
          <p className="text-lg font-semibold text-slate-700">
            문제를 준비하고 있습니다.
          </p>
        </section>
      </main>
    );
  }

  if (isComplete) {
    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>

          <div className="flex flex-wrap gap-3">
            <button
              type="button"
              onClick={resetSession}
              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>
    );
  }

  if (!currentProblem) {
    return (
      <main className="flex min-h-screen items-center bg-slate-50 px-6 py-12 text-slate-950">
        <section className="mx-auto w-full max-w-3xl">
          <p className="text-lg font-semibold text-slate-700">
            현재 문제를 불러올 수 없습니다.
          </p>
        </section>
      </main>
    );
  }

  const submitted = currentResult !== null;
  const isLastProblem = session.currentIndex === session.problems.length - 1;

  return (
    <main className="min-h-screen bg-slate-50 px-6 py-10 text-slate-950">
      <section className="mx-auto flex w-full max-w-3xl flex-col gap-8">
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div className="space-y-2">
            <p className="text-sm font-semibold text-emerald-700">
              괄호 음수 분배
            </p>
            <h1 className="text-3xl font-bold tracking-normal sm:text-4xl">
              문제 풀이
            </h1>
          </div>
          <p className="rounded-md bg-white px-4 py-2 text-sm font-semibold text-slate-700 shadow-sm ring-1 ring-slate-200">
            {session.currentIndex + 1} / {session.problems.length}
          </p>
        </div>

        <div className="rounded-md bg-white p-6 shadow-sm ring-1 ring-slate-200 sm:p-8">
          <p className="mb-4 text-sm font-semibold text-slate-500">
            괄호를 풀어 두 항을 순서대로 입력하세요.
          </p>
          <div className="text-3xl font-semibold text-slate-950 sm:text-4xl">
            <KatexRenderer latex={currentProblem.latexBefore} displayMode />
          </div>
        </div>

        <form
          onSubmit={handleSubmit}
          className="rounded-md bg-white p-6 shadow-sm ring-1 ring-slate-200 sm:p-8"
        >
          <div className="grid gap-4 sm:grid-cols-2">
            <label className="flex flex-col gap-2 text-sm font-semibold text-slate-700">
              첫째 항
              <input
                value={answerA}
                onChange={(event) => setAnswerA(event.target.value)}
                disabled={submitted}
                inputMode="numeric"
                className="h-12 rounded-md border border-slate-300 px-4 text-lg font-semibold text-slate-950 outline-none transition focus:border-emerald-600 focus:ring-2 focus:ring-emerald-200 disabled:bg-slate-100"
              />
            </label>
            <label className="flex flex-col gap-2 text-sm font-semibold text-slate-700">
              둘째 항
              <input
                value={answerB}
                onChange={(event) => setAnswerB(event.target.value)}
                disabled={submitted}
                inputMode="numeric"
                className="h-12 rounded-md border border-slate-300 px-4 text-lg font-semibold text-slate-950 outline-none transition focus:border-emerald-600 focus:ring-2 focus:ring-emerald-200 disabled:bg-slate-100"
              />
            </label>
          </div>

          {inputError ? (
            <p className="mt-3 text-sm font-semibold text-red-700">
              {inputError}
            </p>
          ) : null}

          <div className="mt-6 flex flex-wrap gap-3">
            <button
              type="submit"
              disabled={submitted}
              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 disabled:cursor-not-allowed disabled:bg-slate-300"
            >
              제출
            </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-slate-50 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2"
            >
              처음으로
            </Link>
          </div>
        </form>

        {currentResult ? (
          <div
            className={`rounded-md p-6 shadow-sm ring-1 ${
              currentResult.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">
              {currentResult.correct ? "정답입니다." : "오답입니다."}
            </p>
            <div className="mt-3 text-xl font-semibold">
              <KatexRenderer latex={currentProblem.latexAfter} />
            </div>
            <button
              type="button"
              onClick={nextProblem}
              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>
        ) : null}
      </section>
    </main>
  );
}
