"use client"

import { Plus, Trash2 } from "lucide-react"
import { useTranslations } from "next-intl"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import type { ExamNode } from "./assembly/selected-question-list"
import type { EditableQuestionContent } from "./exam-form-types"

type QuestionSubQuestionsEditorProps = {
  selectedQuestionId: string
  selectedContent: EditableQuestionContent
  updatePreviewQuestionNode: (questionId: string, updater: (node: ExamNode) => ExamNode) => void
  parseEditableContent: (raw: unknown) => EditableQuestionContent
}

export function QuestionSubQuestionsEditor({
  selectedQuestionId,
  selectedContent,
  updatePreviewQuestionNode,
  parseEditableContent,
}: QuestionSubQuestionsEditorProps) {
  const t = useTranslations("examHomework")
  return (
    <div className="space-y-2 rounded-md border p-3">
      <div className="flex items-center justify-between">
        <Label>{t("exam.subQuestions.title")}</Label>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={() => {
            updatePreviewQuestionNode(selectedQuestionId, (node) => {
              if (!node.question) return node
              const current = parseEditableContent(node.question.content)
              return {
                ...node,
                question: {
                  ...node.question,
                  content: {
                    ...current,
                    subQuestions: [
                      ...current.subQuestions,
                      { id: String(current.subQuestions.length + 1), text: "", answer: "", score: undefined },
                    ],
                  },
                },
              }
            })
          }}
        >
          <Plus className="mr-1 h-3.5 w-3.5" />
          {t("exam.subQuestions.add")}
        </Button>
      </div>
      {selectedContent.subQuestions.length > 0 ? (
        <div className="space-y-2">
          {selectedContent.subQuestions.map((item, subIndex) => (
            <div key={`${item.id}-${subIndex}`} className="grid grid-cols-[64px_1fr_1fr_84px_36px] items-center gap-2 rounded-md border p-2">
              <Input
                value={item.id}
                onChange={(event) => {
                  const nextId = event.target.value
                  updatePreviewQuestionNode(selectedQuestionId, (node) => {
                    if (!node.question) return node
                    const current = parseEditableContent(node.question.content)
                    const subQuestions = current.subQuestions.map((row, idx) => idx === subIndex ? { ...row, id: nextId } : row)
                    return { ...node, question: { ...node.question, content: { ...current, subQuestions } } }
                  })
                }}
              />
              <Input
                value={item.text}
                placeholder={t("exam.subQuestions.contentPlaceholder")}
                onChange={(event) => {
                  const text = event.target.value
                  updatePreviewQuestionNode(selectedQuestionId, (node) => {
                    if (!node.question) return node
                    const current = parseEditableContent(node.question.content)
                    const subQuestions = current.subQuestions.map((row, idx) => idx === subIndex ? { ...row, text } : row)
                    return { ...node, question: { ...node.question, content: { ...current, subQuestions } } }
                  })
                }}
              />
              <Input
                value={item.answer ?? ""}
                placeholder={t("exam.subQuestions.answerPlaceholder")}
                onChange={(event) => {
                  const answer = event.target.value
                  updatePreviewQuestionNode(selectedQuestionId, (node) => {
                    if (!node.question) return node
                    const current = parseEditableContent(node.question.content)
                    const subQuestions = current.subQuestions.map((row, idx) => idx === subIndex ? { ...row, answer } : row)
                    return { ...node, question: { ...node.question, content: { ...current, subQuestions } } }
                  })
                }}
              />
              <Input
                type="number"
                min={0}
                value={typeof item.score === "number" ? item.score : ""}
                placeholder={t("exam.subQuestions.scorePlaceholder")}
                onChange={(event) => {
                  const next = Number.parseInt(event.target.value, 10)
                  updatePreviewQuestionNode(selectedQuestionId, (node) => {
                    if (!node.question) return node
                    const current = parseEditableContent(node.question.content)
                    const subQuestions = current.subQuestions.map((row, idx) => idx === subIndex
                      ? { ...row, score: Number.isFinite(next) ? next : undefined }
                      : row)
                    return { ...node, question: { ...node.question, content: { ...current, subQuestions } } }
                  })
                }}
              />
              <Button
                type="button"
                variant="ghost"
                size="icon"
                onClick={() => {
                  updatePreviewQuestionNode(selectedQuestionId, (node) => {
                    if (!node.question) return node
                    const current = parseEditableContent(node.question.content)
                    const subQuestions = current.subQuestions.filter((_, idx) => idx !== subIndex)
                    return { ...node, question: { ...node.question, content: { ...current, subQuestions } } }
                  })
                }}
              >
                <Trash2 className="h-3.5 w-3.5" />
              </Button>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-xs text-muted-foreground">{t("exam.subQuestions.empty")}</div>
      )}
    </div>
  )
}
