"use client" import { useState, useTransition, useEffect } from "react" import { Plus } from "lucide-react" import { toast } from "sonner" import { useTranslations } from "next-intl" import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, DialogFooter, } from "@/shared/components/ui/dialog" import { Button } from "@/shared/components/ui/button" import { Label } from "@/shared/components/ui/label" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/shared/components/ui/select" import { Textarea } from "@/shared/components/ui/textarea" import { createErrorBookItemAction } from "../actions" import { COMMON_ERROR_TAGS } from "../types" interface QuestionOption { id: string preview: string } interface AddErrorBookDialogProps { /** 预加载的题目选项(若提供则直接使用,不再调用 onLoadQuestions) */ questionOptions?: QuestionOption[] /** 懒加载题目选项的回调(对话框打开时调用) */ onLoadQuestions?: () => Promise } export function AddErrorBookDialog({ questionOptions: questionOptionsProp, onLoadQuestions, }: AddErrorBookDialogProps) { const t = useTranslations("error-book") const [open, setOpen] = useState(false) const [isPending, startTransition] = useTransition() const [questionId, setQuestionId] = useState("") const [note, setNote] = useState("") const [errorTags, setErrorTags] = useState([]) const [loadedOptions, setLoadedOptions] = useState([]) const questionOptions = questionOptionsProp ?? loadedOptions useEffect(() => { if (open && onLoadQuestions && loadedOptions.length === 0 && !questionOptionsProp) { onLoadQuestions() .then((options) => { setLoadedOptions(options) }) .catch(() => {}) } }, [open, onLoadQuestions, loadedOptions.length, questionOptionsProp]) function toggleTag(tag: string) { setErrorTags((prev) => prev.includes(tag) ? prev.filter((t) => t !== tag) : [...prev, tag] ) } function handleSubmit() { if (!questionId) { toast.error(t("messages.selectQuestion")) return } startTransition(async () => { const formData = new FormData() formData.append( "json", JSON.stringify({ questionId, note, errorTags }) ) const res = await createErrorBookItemAction(undefined, formData) if (res.success) { toast.success(res.message ?? t("messages.addedShort")) setOpen(false) setQuestionId("") setNote("") setErrorTags([]) } else { toast.error(res.message ?? t("messages.addFailed")) } }) } return ( {t("addDialog.title")} {t("addDialog.description")}