"use client"; import { useCallback, useEffect, useState } from "react"; import { BookOpen, FileText, Loader2, Plus, Trash2, X } from "lucide-react"; import { useTranslation } from "react-i18next"; import { fetchAllProgress, importFromBook, initModules, listBooks, generateModulesFromNotebook, type BookSummary, type ModuleInit, } from "@/lib/learning-api"; import { listKnowledgeBases, type KnowledgeBaseSummary } from "@/lib/knowledge-api"; import { listNotebooks, getNotebook, type NotebookSummary, type NotebookRecordItem, } from "@/lib/notebook-api"; interface CreateModuleDialogProps { open: boolean; onClose: () => void; onCreated: () => void; } type TabKey = "manual" | "book" | "kb" | "notebook"; interface KpRow { name: string; type: string; } export default function CreateModuleDialog({ open, onClose, onCreated, }: CreateModuleDialogProps) { const { t } = useTranslation(); const [tab, setTab] = useState("manual"); // ── Manual tab state ── const [moduleName, setModuleName] = useState(""); const [kpRows, setKpRows] = useState([{ name: "", type: "concept" }]); const [manualBookId, setManualBookId] = useState("manual"); // ── Book tab state ── const [books, setBooks] = useState([]); const [selectedBookId, setSelectedBookId] = useState(""); const [bookChapters, setBookChapters] = useState<{ title: string; learning_objectives: string[] }[]>([]); const [loadingBooks, setLoadingBooks] = useState(false); const [loadingChapters, setLoadingChapters] = useState(false); // ── KB tab state ── const [kbList, setKbList] = useState([]); const [selectedKb, setSelectedKb] = useState(""); const [loadingKb, setLoadingKb] = useState(false); // ── Notebook tab state ── const [notebooks, setNotebooks] = useState([]); const [selectedNotebook, setSelectedNotebook] = useState(""); const [notebookRecords, setNotebookRecords] = useState([]); const [selectedRecordIds, setSelectedRecordIds] = useState>(new Set()); const [loadingNotebooks, setLoadingNotebooks] = useState(false); const [loadingRecords, setLoadingRecords] = useState(false); // ── Shared state ── const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); // Load data when tab changes useEffect(() => { if (!open) return; if (tab === "book" && books.length === 0) { setLoadingBooks(true); listBooks() .then(setBooks) .catch(() => setError(t("guidedLearning.loadBooksFailed"))) .finally(() => setLoadingBooks(false)); } if (tab === "kb" && kbList.length === 0) { setLoadingKb(true); listKnowledgeBases() .then(setKbList) .catch(() => setError(t("guidedLearning.loadKbFailed"))) .finally(() => setLoadingKb(false)); } if (tab === "notebook" && notebooks.length === 0) { setLoadingNotebooks(true); listNotebooks() .then(setNotebooks) .catch(() => setError(t("guidedLearning.loadNotebooksFailed"))) .finally(() => setLoadingNotebooks(false)); } }, [open, tab, books.length, kbList.length, notebooks.length, t]); // Load chapters when book selected useEffect(() => { if (!selectedBookId) { setBookChapters([]); return; } setLoadingChapters(true); import("@/lib/book-api").then(({ bookApi }) => bookApi.get(selectedBookId) .then((data) => setBookChapters(data.spine?.chapters ?? [])) .catch(() => setError(t("guidedLearning.loadChaptersFailed"))) .finally(() => setLoadingChapters(false)), ); }, [selectedBookId, t]); // Load records when notebook selected useEffect(() => { if (!selectedNotebook) { setNotebookRecords([]); setSelectedRecordIds(new Set()); return; } setLoadingRecords(true); getNotebook(selectedNotebook) .then((data) => setNotebookRecords(data.records ?? [])) .catch(() => setError(t("guidedLearning.loadRecordsFailed"))) .finally(() => setLoadingRecords(false)); }, [selectedNotebook, t]); const resetState = useCallback(() => { setTab("manual"); setModuleName(""); setKpRows([{ name: "", type: "concept" }]); setManualBookId("manual"); setSelectedBookId(""); setBookChapters([]); setSelectedKb(""); setSelectedNotebook(""); setNotebookRecords([]); setSelectedRecordIds(new Set()); setSubmitting(false); setError(null); }, []); const handleClose = useCallback(() => { resetState(); onClose(); }, [resetState, onClose]); // ── Submit handlers ── const handleManualSubmit = async () => { const validKps = kpRows.filter((r) => r.name.trim()); if (!moduleName.trim() && validKps.length === 0) { setError(t("guidedLearning.moduleNameRequired")); return; } setSubmitting(true); setError(null); try { const bookId = manualBookId.trim() || "manual"; const modules: ModuleInit[] = [{ id: `${bookId}_m0`, name: moduleName.trim() || t("guidedLearning.untitledModule"), order: 0, pass_threshold: 0.7, knowledge_points: validKps.map((kp, j) => ({ id: `${bookId}_m0_kp${j}`, name: kp.name.trim(), type: kp.type, module_id: `${bookId}_m0`, })), }]; await initModules(bookId, modules); onCreated(); handleClose(); } catch { setError(t("guidedLearning.createModuleFailed")); } finally { setSubmitting(false); } }; const handleBookSubmit = async () => { if (!selectedBookId || bookChapters.length === 0) return; setSubmitting(true); setError(null); try { const chapters = bookChapters.map((ch) => ({ title: ch.title, knowledge_points: ch.learning_objectives ?? [], })); await importFromBook(selectedBookId, chapters); onCreated(); handleClose(); } catch { setError(t("guidedLearning.importBookFailed")); } finally { setSubmitting(false); } }; const handleKbSubmit = async () => { if (!selectedKb) return; setSubmitting(true); setError(null); try { const bookId = `kb_${selectedKb}`; // For KB import, we create a single module with the KB name // The actual LLM-based module generation would need a dedicated endpoint const modules: ModuleInit[] = [{ id: `${bookId}_m0`, name: selectedKb, order: 0, pass_threshold: 0.7, knowledge_points: [], }]; await initModules(bookId, modules); onCreated(); handleClose(); } catch { setError(t("guidedLearning.importKbFailed")); } finally { setSubmitting(false); } }; const handleNotebookSubmit = async () => { if (!selectedNotebook || selectedRecordIds.size === 0) return; setSubmitting(true); setError(null); try { const bookId = `nb_${selectedNotebook}`; const records = notebookRecords .filter((r) => selectedRecordIds.has(r.id)) .map((r) => ({ id: r.id, type: r.type, title: r.title, output: r.output })); const result = await generateModulesFromNotebook(bookId, selectedNotebook, records.slice(0, 20)); // After LLM generates, init the modules if (result.modules && result.modules.length > 0) { await initModules(bookId, result.modules); } onCreated(); handleClose(); } catch { setError(t("guidedLearning.importNotebookFailed")); } finally { setSubmitting(false); } }; if (!open) return null; const tabs: { key: TabKey; label: string }[] = [ { key: "manual", label: t("guidedLearning.tabManual") }, { key: "book", label: t("guidedLearning.tabBook") }, { key: "kb", label: t("guidedLearning.tabKb") }, { key: "notebook", label: t("guidedLearning.tabNotebook") }, ]; return (
{/* Backdrop */}
{/* Dialog */}
{/* Header */}

{t("guidedLearning.createModule")}

{/* Tabs */}
{tabs.map((tb) => ( ))}
{/* Content */}
{error && (
{error}
)} {/* Manual Tab */} {tab === "manual" && (
setManualBookId(e.target.value)} placeholder="manual" className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none" />
setModuleName(e.target.value)} placeholder={t("guidedLearning.moduleNamePlaceholder")} className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none" />
{kpRows.map((row, i) => (
{ const next = [...kpRows]; next[i] = { ...next[i], name: e.target.value }; setKpRows(next); }} placeholder={t("guidedLearning.kpNamePlaceholder")} className="flex-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none" /> {kpRows.length > 1 && ( )}
))}
)} {/* Book Tab */} {tab === "book" && (
{loadingBooks ? (
) : books.length === 0 ? (
{t("guidedLearning.noBooks")}
) : ( <>
{books.map((book) => ( ))}
{selectedBookId && (
{loadingChapters ? (
{t("guidedLearning.loadingChapters")}
) : bookChapters.length === 0 ? (
{t("guidedLearning.noChapters")}
) : (

{t("guidedLearning.chaptersToImport", { count: bookChapters.length })}

{bookChapters.map((ch, i) => (
{ch.title} ({(ch.learning_objectives ?? []).length} {t("guidedLearning.kps")})
))}
)}
)} )}
)} {/* KB Tab */} {tab === "kb" && (
{loadingKb ? (
) : kbList.length === 0 ? (
{t("guidedLearning.noKb")}
) : (
{kbList.map((kb) => ( ))}
)}
)} {/* Notebook Tab */} {tab === "notebook" && (
{loadingNotebooks ? (
) : notebooks.length === 0 ? (
{t("guidedLearning.noNotebooks")}
) : ( <>
{notebooks.map((nb) => ( ))}
{selectedNotebook && (
{loadingRecords ? (
{t("guidedLearning.loadingRecords")}
) : notebookRecords.length === 0 ? (
{t("guidedLearning.noRecords")}
) : (

{t("guidedLearning.selectRecords")} ({selectedRecordIds.size} {t("guidedLearning.selected")})

{notebookRecords.slice(0, 20).map((rec) => ( ))}
{notebookRecords.length > 20 && (

{t("guidedLearning.recordsLimited")}

)}
)}
)} )}
)}
{/* Footer */}
); }