import { useCallback, useEffect, useRef, useState } from "react" import { Link, useParams } from "react-router-dom" import { ArrowDown, ArrowLeft, ArrowUp, BookOpen, Pencil, Plus, Trash2 } from "lucide-react" import { toast } from "sonner" import http from "../../api/http" import { Button } from "../../components/ui/button" import { Input } from "../../components/ui/input" import { Textarea } from "../../components/ui/textarea" import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../../components/ui/dialog" import { notifyApiError } from "../../lib/apiErrors" import { createChapterQuiz, getLearningItem, listLearningItems as allItems, learningCollections as collection, updateChapterQuiz, type LearningItem as Item, type LearningKind as Kind, } from "../../api/learningHierarchy.api" type Editor = { kind: Kind; item?: Item } export function LearningHierarchyPage() { const { courseId, chapterId } = useParams<{ courseId: string; chapterId: string }>() const kind: Kind = chapterId ? "lesson" : courseId ? "chapter" : "course" const path = chapterId ? `/chapters/${chapterId}/lessons` : courseId ? `/courses/${courseId}/chapters` : "/courses" const activePath = useRef(path) const requestVersion = useRef(0) useEffect(() => { activePath.current = path; return () => { requestVersion.current += 1 } }, [path]) const [items, setItems] = useState([]) const [quizzes, setQuizzes] = useState([]) const [course, setCourse] = useState(null) const [chapter, setChapter] = useState(null) const [loading, setLoading] = useState(true) const [failed, setFailed] = useState(false) const [busy, setBusy] = useState(false) const [search, setSearch] = useState("") const [showLegacy, setShowLegacy] = useState(false) const [editor, setEditor] = useState(null) const [deleting, setDeleting] = useState<{ item: Item; kind: Kind } | null>(null) const [form, setForm] = useState({ name: "", description: "", thumbnail: "", video_url: "", access_tier: "FREE" }) const load = useCallback(async () => { if (activePath.current !== path) return const version = ++requestVersion.current setLoading(true); setFailed(false) try { const [rows, quizRows, courseRes, chapterRes] = await Promise.all([ allItems(path, collection[kind]), chapterId ? allItems(`/chapters/${chapterId}/quizzes`, "quizzes") : Promise.resolve([]), courseId ? getLearningItem("course", Number(courseId)) : Promise.resolve(null), chapterId ? getLearningItem("chapter", Number(chapterId)) : Promise.resolve(null), ]) if (version !== requestVersion.current || activePath.current !== path) return if (chapterRes && chapterRes.course_id !== Number(courseId)) { throw new Error("This chapter does not belong to the selected course") } setItems(rows); setQuizzes(quizRows); setCourse(courseRes); setChapter(chapterRes) } catch (error) { if (version === requestVersion.current && activePath.current === path) { setFailed(true); notifyApiError(error, "Unable to load learning content") } } finally { if (version === requestVersion.current && activePath.current === path) setLoading(false) } }, [path, kind, courseId, chapterId]) useEffect(() => { setSearch(""); void load() }, [load]) function openEditor(next: Editor) { setEditor(next) const item = next.item setForm({ name: item?.name ?? item?.title ?? "", description: item?.description ?? "", thumbnail: item?.thumbnail ?? "", video_url: item?.video_url ?? "", access_tier: item?.access_tier ?? "FREE" }) } async function save(event: React.FormEvent) { event.preventDefault() if (!editor || busy || !form.name.trim()) return setBusy(true) try { const payload = { ...form, name: form.name.trim() } if (editor.kind === "quiz") { if (editor.item) { await updateChapterQuiz(editor.item.id, { title: form.name.trim() }) } else { await createChapterQuiz(Number(chapterId), form.name.trim()) } } else { const body = editor.kind === "lesson" ? { title: payload.name, description: payload.description, thumbnail: payload.thumbnail, video_url: payload.video_url, access_tier: payload.access_tier } : payload if (editor.item) await http.put(`/${collection[editor.kind]}/${editor.item.id}`, body) else await http.post(path, { ...body, publish_status: "DRAFT" }) } setEditor(null); toast.success(`${editor.kind} saved`); await load() } catch (error) { notifyApiError(error, "Unable to save content") } finally { setBusy(false) } } async function publish(item: Item, itemKind: Kind) { setBusy(true) try { const status = item.publish_status === "PUBLISHED" ? "DRAFT" : "PUBLISHED" if (itemKind === "quiz") await updateChapterQuiz(item.id, { publish_status: status }) else await http.put(`/${collection[itemKind]}/${item.id}`, { publish_status: status }) await load() } catch (error) { notifyApiError(error, "Unable to change publication status") } finally { setBusy(false) } } async function remove() { if (!deleting) return setBusy(true) try { await http.delete(`/${collection[deleting.kind]}/${deleting.item.id}`); setDeleting(null); await load() } catch (error) { notifyApiError(error, "Unable to delete content") } finally { setBusy(false) } } const movableIndices = items.flatMap((item, index) => kind !== "course" || !item.is_archived ? [index] : []) async function move(index: number, direction: number) { const ordered = [...items]; const target = movableIndices[movableIndices.indexOf(index) + direction] if (target === undefined) return ;[ordered[index], ordered[target]] = [ordered[target], ordered[index]] setBusy(true) try { await http.put(`${path}/reorder`, { ordered_ids: ordered.map(item => item.id) }); setItems(ordered) } catch (error) { notifyApiError(error, "Unable to reorder content") } finally { setBusy(false) } } const title = chapter?.name ?? course?.name ?? "Courses" const matches = (item: Item) => (kind !== "course" || !!item.is_archived === showLegacy) && (item.name ?? item.title ?? "").toLowerCase().includes(search.toLowerCase()) function card(item: Item, itemKind: Kind, index?: number) { return

{item.name ?? item.title}

{item.publish_status === "PUBLISHED" ? "Published" : "Draft"}{item.access_tier ? ` · ${item.access_tier.toLowerCase()}` : ""}

{index !== undefined && !search && !showLegacy && <>}
{item.description &&

{item.description}

} {item.video_url && View lesson video}
{itemKind === "course" && } {itemKind === "chapter" && } {itemKind === "quiz" && }
} return

{title}

{chapterId ? "Manage the lessons and quizzes in this chapter." : courseId ? "Organize this course into chapters." : "Create courses, organize chapters, and add lessons and chapter quizzes."}

{courseId && } {kind === "course" &&
{showLegacy &&

Retired general-learning fixtures are kept here to preserve historical records and learner progress. They are unavailable in the learner catalog.

}
} setSearch(event.target.value)} /> {loading ?

Loading content…

: failed ?

Content could not be loaded.

: <>

{collection[kind]}

{items.map((item, index) => matches(item) ? card(item, kind, index) : null)}
{!items.some(matches) &&

{search ? "No matching content." : showLegacy ? "No archived courses." : `No ${collection[kind]} yet. Add your first ${kind} to get started.`}

}
{chapterId &&

Chapter quizzes

{quizzes.filter(matches).map(item => card(item, "quiz"))}
{!quizzes.some(matches) &&

{search ? "No matching quizzes." : "No quizzes yet. Create a quiz, add its questions, then publish it."}

}
} } { if (!open && !busy) setEditor(null) }}>{editor?.item ? "Edit" : "Add"} {editor?.kind}
{editor?.kind !== "quiz" && <>