"use client";

/**
 * PracticeSession — 练习会话答题（批次 A）
 *
 * 数据源：useStartPracticeSession（加载会话题目）+ useSubmitPracticeAnswer
 * 视图：当前题目 + 选项/作答区 + 进度指示 + 答题反馈
 */

import { useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import {
  useStartPracticeSession,
  useSubmitPracticeAnswer,
} from "@/lib/graphql/hooks";
import type { PracticeQuestion } from "@/lib/graphql/types";

export default function PracticeSessionPage(): JSX.Element {
  const params = useParams();
  const sessionId = params["sessionId"] as string;

  const { data: sessionData, fetching, error, execute: startExecute } = useStartPracticeSession();
  const { execute: submitExecute, data: submitResult, fetching: submitting } = useSubmitPracticeAnswer();
  const [currentIndex, setCurrentIndex] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState<string>("");
  const [textAnswer, setTextAnswer] = useState<string>("");
  const [feedback, setFeedback] = useState<null | { isCorrect: boolean; correctAnswer: string }>(null);
  const [started, setStarted] = useState(false);

  useEffect(() => {
    if (!started) {
      startExecute({ practiceType: "error_variant", questionCount: 10 });
      setStarted(true);
    }
  }, [started, startExecute]);

  const session = sessionData?.session ?? null;
  const questions = session?.questions ?? [];
  const currentQuestion: PracticeQuestion | undefined = questions[currentIndex];

  const handleSubmit = (): void => {
    if (!currentQuestion) return;
    const answer = currentQuestion.type === "single-choice" ? selectedAnswer : textAnswer;
    if (!answer) return;
    submitExecute({ sessionId: session?.id ?? sessionId, questionId: currentQuestion.questionId, answer });
    setFeedback(null);
  };

  useEffect(() => {
    if (submitResult) {
      setFeedback({
        isCorrect: submitResult.isCorrect,
        correctAnswer: submitResult.correctAnswer,
      });
    }
  }, [submitResult]);

  const handleNext = (): void => {
    setCurrentIndex((i) => i + 1);
    setSelectedAnswer("");
    setTextAnswer("");
    setFeedback(null);
  };

  if (fetching && !session) {
    return (
      <div className="px-6 lg:px-10 py-8 max-w-3xl mx-auto">
        <p className="text-sm" style={{ color: "var(--color-ink-muted)" }} aria-live="polite">
          正在加载练习题目…
        </p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="px-6 lg:px-10 py-8 max-w-3xl mx-auto">
        <div role="alert" className="card-paper p-6" style={{ borderColor: "var(--color-danger)" }}>
          <p className="text-sm" style={{ color: "var(--color-danger)" }}>
            练习加载失败：{error.message}
          </p>
          <Link href="/practice" className="mt-4 inline-block btn-secondary text-xs">
            返回练习列表
          </Link>
        </div>
      </div>
    );
  }

  if (!session || !currentQuestion) {
    return (
      <div className="px-6 lg:px-10 py-8 max-w-3xl mx-auto">
        <div className="card-paper p-8 text-center">
          <p className="text-base font-serif" style={{ color: "var(--color-ink)" }}>
            练习已结束
          </p>
          <p className="mt-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
            {session
              ? `已答题 ${session.answeredQuestions}/${session.totalQuestions}，正确 ${session.correctCount} 题`
              : "未找到练习会话"}
          </p>
          <Link href="/practice" className="mt-4 inline-block btn-secondary text-xs">
            返回练习列表
          </Link>
        </div>
      </div>
    );
  }

  const progress = session.totalQuestions > 0 ? (currentIndex / session.totalQuestions) * 100 : 0;

  return (
    <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-3xl mx-auto">
      <Link href="/practice" className="text-xs" style={{ color: "var(--color-ink-muted)" }}>
        ← 退出练习
      </Link>

      <div className="mt-4 mb-6">
        <div className="flex items-center justify-between mb-2">
          <span className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
            第 {currentIndex + 1} / {session.totalQuestions} 题
          </span>
          <span className="text-xs" style={{ color: "var(--color-ink-muted)" }}>
            已答 {session.answeredQuestions} · 正确 {session.correctCount}
          </span>
        </div>
        <div className="h-1 rounded-sm overflow-hidden" style={{ background: "var(--color-rule)" }}>
          <div
            className="h-full transition-all"
            style={{ width: `${progress}%`, background: "var(--color-accent)" }}
          />
        </div>
      </div>

      <article className="card-paper p-6 mb-6">
        <p className="text-base font-serif mb-4" style={{ color: "var(--color-ink)" }}>
          {currentQuestion.content}
        </p>

        {currentQuestion.type === "single-choice" && currentQuestion.options.length > 0 ? (
          <ul className="space-y-2">
            {currentQuestion.options.map((opt) => (
              <li key={opt.id}>
                <label
                  className="flex items-center gap-3 p-3 rounded-sm cursor-pointer transition-colors"
                  style={{
                    background: selectedAnswer === opt.id ? "var(--color-accent-muted)" : "var(--color-paper)",
                    border: `1px solid ${selectedAnswer === opt.id ? "var(--color-accent)" : "var(--color-rule)"}`,
                  }}
                >
                  <input
                    type="radio"
                    name="answer"
                    value={opt.id}
                    checked={selectedAnswer === opt.id}
                    onChange={(e) => setSelectedAnswer(e.target.value)}
                    disabled={feedback !== null}
                  />
                  <span className="text-sm" style={{ color: "var(--color-ink)" }}>
                    {opt.text}
                  </span>
                </label>
              </li>
            ))}
          </ul>
        ) : (
          <textarea
            value={textAnswer}
            onChange={(e) => setTextAnswer(e.target.value)}
            disabled={feedback !== null}
            rows={4}
            placeholder="请输入你的答案..."
            className="w-full px-3 py-2 rounded-sm text-sm"
            style={{
              background: "var(--color-paper)",
              border: "1px solid var(--color-rule)",
              color: "var(--color-ink)",
            }}
          />
        )}

        {feedback && (
          <div
            className="mt-4 p-4 rounded-sm"
            style={{
              background: feedback.isCorrect ? "var(--color-success-muted, rgba(34,197,94,0.1))" : "rgba(239,68,68,0.1)",
              border: `1px solid ${feedback.isCorrect ? "var(--color-success)" : "var(--color-danger)"}`,
            }}
          >
            <p
              className="text-sm font-serif"
              style={{ color: feedback.isCorrect ? "var(--color-success)" : "var(--color-danger)" }}
            >
              {feedback.isCorrect ? "回答正确！" : "回答错误"}
            </p>
            {!feedback.isCorrect && (
              <p className="mt-1 text-xs" style={{ color: "var(--color-ink-muted)" }}>
                正确答案：{feedback.correctAnswer}
              </p>
            )}
          </div>
        )}
      </article>

      <div className="flex gap-3">
        {!feedback ? (
          <button
            type="button"
            onClick={handleSubmit}
            disabled={submitting || (!selectedAnswer && !textAnswer)}
            className="btn-primary text-sm disabled:opacity-50"
          >
            {submitting ? "提交中..." : "提交答案"}
          </button>
        ) : (
          <button type="button" onClick={handleNext} className="btn-primary text-sm">
            下一题
          </button>
        )}
      </div>
    </div>
  );
}
