"use client"

import { useTranslations } from "next-intl"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"

import { QuestionContent } from "./question-content"
import { AnswerInput } from "./answer-input"
import { AnswerResult } from "./answer-result"
import type { PracticeAnswerRecord } from "../types"

interface QuestionCardProps {
  answer: PracticeAnswerRecord
  index: number
  total: number
  userAnswer: unknown
  onAnswerChange: (answer: unknown) => void
  onSubmit: (answer: unknown) => void
  onSkip: () => void
  onRetry?: () => void
  isAnswered: boolean
  result?: { isCorrect: boolean | null; score: number | null }
  isPending: boolean
  /** 提交是否失败（用于显示重试按钮） */
  submitFailed?: boolean
}

/**
 * 题目卡片组件。
 *
 * 展示单道题目及其作答/结果区域，负责：
 * - 题目元信息（类型、难度、变式标记）
 * - 题目内容（使用 QuestionContent 替代 JSON.stringify）
 * - 作答输入（未作答时）或结果展示（已作答时）
 * - 操作按钮（提交、跳过、重试）
 */
export function QuestionCard({
  answer,
  index,
  total,
  userAnswer,
  onAnswerChange,
  onSubmit,
  onSkip,
  onRetry,
  isAnswered,
  result,
  isPending,
  submitFailed = false,
}: QuestionCardProps): React.ReactNode {
  const t = useTranslations("practice")

  const question = answer.question
  const content = answer.variantContent ?? question?.content
  const questionType = question?.type ?? "unknown"

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="text-base">
            {t("session.question")} {index + 1}/{total}
          </CardTitle>
          <div className="flex items-center gap-2">
            <Badge variant="outline" aria-label={`题型: ${questionType}`}>
              {questionType}
            </Badge>
            {question?.difficulty ? (
              <Badge variant="secondary" aria-label={`难度: ${question.difficulty}`}>
                {t("session.difficulty")}: {question.difficulty}
              </Badge>
            ) : null}
            {answer.isVariant ? (
              <Badge variant="default" aria-label={t("session.variant")}>
                {t("session.variant")}
              </Badge>
            ) : null}
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 题目内容 */}
        <div
          className="rounded-md border bg-muted/30 p-4 text-sm"
          role="region"
          aria-label={`题目 ${index + 1}`}
        >
          <QuestionContent content={content} />
        </div>

        {/* 作答区域 */}
        {!isAnswered ? (
          <AnswerInput
            questionType={questionType}
            content={content}
            userAnswer={userAnswer}
            onAnswerChange={onAnswerChange}
            disabled={isPending}
          />
        ) : (
          <AnswerResult answer={answer} result={result} />
        )}

        {/* 提交失败提示 + 重试 */}
        {submitFailed && !isAnswered ? (
          <div
            className="rounded-md border border-rose-200 bg-rose-50/50 p-3 text-sm text-rose-700 dark:border-rose-900 dark:bg-rose-950/20 dark:text-rose-400"
            role="alert"
            aria-live="assertive"
          >
            {t("session.submitFailedDescription")}
          </div>
        ) : null}

        {/* 操作按钮 */}
        {!isAnswered ? (
          <div className="flex justify-end gap-2">
            <Button
              variant="ghost"
              onClick={onSkip}
              disabled={isPending}
              aria-label={t("session.skip")}
            >
              {t("session.skip")}
            </Button>
            {submitFailed && onRetry ? (
              <Button
                variant="outline"
                onClick={onRetry}
                disabled={isPending}
                aria-label={t("session.retry")}
              >
                {t("session.retry")}
              </Button>
            ) : null}
            <Button
              onClick={() => onSubmit(userAnswer)}
              disabled={isPending || userAnswer === undefined}
              aria-label={t("session.submit")}
            >
              {isPending ? t("session.submitting") : t("session.submit")}
            </Button>
          </div>
        ) : null}
      </CardContent>
    </Card>
  )
}
