"use client"

import { Loader2, Wand2 } from "lucide-react"
import { useTranslations } from "next-intl"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Textarea } from "@/shared/components/ui/textarea"
import { Label } from "@/shared/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import type { ExamNode } from "./assembly/selected-question-list"
import type { QuestionType } from "@/modules/questions/types"
import type { EditableQuestionContent } from "./exam-form-types"
import { QuestionOptionsEditor } from "./question-options-editor"
import { QuestionSubQuestionsEditor } from "./question-sub-questions-editor"

const QUESTION_TYPES: readonly QuestionType[] = [
  "single_choice",
  "multiple_choice",
  "text",
  "judgment",
  "composite",
] as const

function isQuestionType(value: string): value is QuestionType {
  return (QUESTION_TYPES as readonly string[]).includes(value)
}

type ExamPreviewQuestionEditorProps = {
  selectedQuestion: ExamNode | null
  selectedContent: EditableQuestionContent | null
  selectedQuestionId: string
  updatePreviewQuestionNode: (questionId: string, updater: (node: ExamNode) => ExamNode) => void
  parseEditableContent: (raw: unknown) => EditableQuestionContent
  rewriteInstruction: string
  setRewriteInstruction: (value: string) => void
  rewritingQuestion: boolean
  handleRewriteSelectedQuestion: () => void
  previewRawOutput: string
}

export function ExamPreviewQuestionEditor({
  selectedQuestion,
  selectedContent,
  selectedQuestionId,
  updatePreviewQuestionNode,
  parseEditableContent,
  rewriteInstruction,
  setRewriteInstruction,
  rewritingQuestion,
  handleRewriteSelectedQuestion,
  previewRawOutput,
}: ExamPreviewQuestionEditorProps) {
  const t = useTranslations("examHomework")
  if (!selectedQuestion?.question || !selectedContent) {
    return <div className="flex-1 py-20 text-center text-muted-foreground">{t("exam.preview.selectQuestionHint")}</div>
  }

  const isChoiceQuestion = selectedQuestion.question.type === "single_choice" || selectedQuestion.question.type === "multiple_choice"

  return (
    <div className="flex-1 min-h-0 flex flex-col">
      <div className="p-4 border-b flex items-center justify-between">
        <div>
          <div className="text-sm font-medium">{t("exam.preview.editorTitle")}</div>
          <div className="text-xs text-muted-foreground mt-1">{t("exam.preview.editorDescription")}</div>
        </div>
      </div>
      <div className="flex-1 overflow-y-auto">
        <div className="p-4 space-y-4">
          <div className="grid grid-cols-3 gap-3">
            <div className="space-y-1">
              <Label>{t("exam.richEditor.questionType")}</Label>
              <Select
                value={selectedQuestion.question.type}
                onValueChange={(value) => {
                  updatePreviewQuestionNode(selectedQuestionId, (node) => {
                    if (!node.question) return node
                    // Use type guard to narrow string to Question["type"] instead of `as` assertion
                    if (!isQuestionType(value)) return node
                    return { ...node, question: { ...node.question, type: value } }
                  })
                }}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="single_choice">single_choice</SelectItem>
                  <SelectItem value="multiple_choice">multiple_choice</SelectItem>
                  <SelectItem value="judgment">judgment</SelectItem>
                  <SelectItem value="text">text</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label>{t("exam.form.difficulty")}</Label>
              <Input
                type="number"
                min={1}
                max={5}
                value={selectedQuestion.question.difficulty ?? 3}
                onChange={(event) => {
                  const next = Number.parseInt(event.target.value || "3", 10)
                  updatePreviewQuestionNode(selectedQuestionId, (node) => {
                    if (!node.question) return node
                    return { ...node, question: { ...node.question, difficulty: Number.isFinite(next) ? next : 3 } }
                  })
                }}
              />
            </div>
            <div className="space-y-1">
              <Label>{t("exam.richEditor.score")}</Label>
              <Input
                type="number"
                min={0}
                value={selectedQuestion.score ?? 0}
                onChange={(event) => {
                  const next = Number.parseInt(event.target.value || "0", 10)
                  updatePreviewQuestionNode(selectedQuestionId, (node) => ({ ...node, score: Number.isFinite(next) ? next : 0 }))
                }}
              />
            </div>
          </div>

          <div className="space-y-1">
            <Label>{t("exam.preview.stem")}</Label>
            <Textarea
              className="min-h-[140px]"
              value={selectedContent.text}
              onChange={(event) => {
                const text = event.target.value
                updatePreviewQuestionNode(selectedQuestionId, (node) => {
                  if (!node.question) return node
                  const current = parseEditableContent(node.question.content)
                  return { ...node, question: { ...node.question, content: { ...current, text } } }
                })
              }}
            />
          </div>

          {isChoiceQuestion ? (
            <QuestionOptionsEditor
              selectedQuestionId={selectedQuestionId}
              selectedContent={selectedContent}
              questionType={selectedQuestion.question.type}
              updatePreviewQuestionNode={updatePreviewQuestionNode}
              parseEditableContent={parseEditableContent}
            />
          ) : null}

          <QuestionSubQuestionsEditor
            selectedQuestionId={selectedQuestionId}
            selectedContent={selectedContent}
            updatePreviewQuestionNode={updatePreviewQuestionNode}
            parseEditableContent={parseEditableContent}
          />

          <div className="rounded-md border p-3 space-y-2">
            <Label>{t("exam.preview.aiRewriteInstruction")}</Label>
            <Textarea
              className="min-h-[90px]"
              placeholder={t("exam.preview.aiRewritePlaceholder")}
              value={rewriteInstruction}
              onChange={(event) => setRewriteInstruction(event.target.value)}
            />
            <div className="flex justify-end">
              <Button type="button" variant="outline" onClick={handleRewriteSelectedQuestion} disabled={rewritingQuestion}>
                {rewritingQuestion ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Wand2 className="mr-2 h-4 w-4" />}
                {t("exam.preview.aiRewriteButton")}
              </Button>
            </div>
          </div>
          {previewRawOutput ? (
            <div className="rounded-md border bg-muted/30 p-3">
              <div className="text-xs font-medium mb-2">{t("exam.preview.rawModelOutput")}</div>
              <pre className="whitespace-pre-wrap text-xs text-muted-foreground">{previewRawOutput}</pre>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  )
}
