RezinaLMS-Admin/src/pages/content-management/LearningHierarchyPage.tsx

159 lines
14 KiB
TypeScript

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<Item[]>([])
const [quizzes, setQuizzes] = useState<Item[]>([])
const [course, setCourse] = useState<Item | null>(null)
const [chapter, setChapter] = useState<Item | null>(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<Editor | null>(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 <article key={item.id} className="rounded-xl border border-grayScale-200 bg-white p-5 dark:bg-grayScale-50">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0"><h3 className="text-lg font-semibold">{item.name ?? item.title}</h3><p className="mt-1 text-sm text-grayScale-500">{item.publish_status === "PUBLISHED" ? "Published" : "Draft"}{item.access_tier ? ` · ${item.access_tier.toLowerCase()}` : ""}</p></div>
<div className="flex gap-1">
{index !== undefined && !search && !showLegacy && <><Button size="icon" variant="ghost" disabled={busy || index === movableIndices[0]} onClick={() => void move(index, -1)} aria-label="Move up"><ArrowUp size={16} /></Button><Button size="icon" variant="ghost" disabled={busy || index === movableIndices[movableIndices.length - 1]} onClick={() => void move(index, 1)} aria-label="Move down"><ArrowDown size={16} /></Button></>}
<Button size="icon" variant="ghost" disabled={busy || item.is_archived} onClick={() => openEditor({ kind: itemKind, item })} aria-label="Edit"><Pencil size={16} /></Button>
<Button size="icon" variant="ghost" disabled={busy || item.is_archived} onClick={() => setDeleting({ item, kind: itemKind })} aria-label="Delete"><Trash2 size={16} /></Button>
</div>
</div>
{item.description && <p className="mt-3 line-clamp-3 text-sm text-grayScale-600">{item.description}</p>}
{item.video_url && <a className="mt-3 block text-sm text-brand-600 underline" href={item.video_url} target="_blank" rel="noreferrer">View lesson video</a>}
<div className="mt-5 flex flex-wrap gap-2">
{itemKind === "course" && <Button asChild variant="outline"><Link to={`/new-content/courses/${item.id}`}>Chapters</Link></Button>}
{itemKind === "chapter" && <Button asChild variant="outline"><Link to={`/new-content/courses/${courseId}/chapters/${item.id}`}>Lessons & quizzes</Link></Button>}
{itemKind === "quiz" && <Button asChild variant="outline"><Link to={`/content/question-sets/${item.question_set_id}/questions`} state={{ from: `/new-content/courses/${courseId}/chapters/${chapterId}` }}>Edit questions</Link></Button>}
<Button variant="outline" disabled={busy || item.is_archived} onClick={() => void publish(item, itemKind)}>{item.is_archived ? "Archived" : item.publish_status === "PUBLISHED" ? "Unpublish" : "Publish"}</Button>
</div>
</article>
}
return <div className="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
<nav className="flex flex-wrap items-center gap-2 text-sm text-grayScale-500"><Link to="/new-content/courses">Courses</Link>{courseId && <><span>/</span><Link to={`/new-content/courses/${courseId}`}>{course?.name ?? "Course"}</Link></>}{chapterId && <><span>/</span><span>{chapter?.name ?? "Chapter"}</span></>}</nav>
<header className="flex flex-wrap items-center justify-between gap-4"><div><h1 className="flex items-center gap-3 text-2xl font-bold"><BookOpen />{title}</h1><p className="mt-2 text-grayScale-500">{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."}</p></div><Button disabled={busy || loading || failed} onClick={() => openEditor({ kind })}><Plus size={16} className="mr-2" />Add {kind}</Button></header>
{courseId && <Button asChild variant="ghost"><Link to={chapterId ? `/new-content/courses/${courseId}` : "/new-content/courses"}><ArrowLeft size={16} className="mr-2" />Back to {chapterId ? "chapters" : "courses"}</Link></Button>}
{kind === "course" && <div className="space-y-3">
<div className="flex flex-wrap gap-2" role="group" aria-label="Course catalog view">
<Button variant={showLegacy ? "outline" : "default"} aria-pressed={!showLegacy} onClick={() => setShowLegacy(false)}>Academy courses</Button>
<Button variant={showLegacy ? "default" : "outline"} aria-pressed={showLegacy} onClick={() => setShowLegacy(true)}>Legacy archive ({items.filter(item => item.is_archived).length})</Button>
</div>
{showLegacy && <p className="text-sm text-grayScale-500">Retired general-learning fixtures are kept here to preserve historical records and learner progress. They are unavailable in the learner catalog.</p>}
</div>}
<Input aria-label="Search content" placeholder="Search by title…" value={search} onChange={event => setSearch(event.target.value)} />
{loading ? <p role="status">Loading content…</p> : failed ? <div role="alert"><p>Content could not be loaded.</p><Button onClick={() => void load()}>Try again</Button></div> : <>
<section className="space-y-4"><h2 className="text-xl font-semibold capitalize">{collection[kind]}</h2><div className="grid gap-4 md:grid-cols-2">{items.map((item, index) => matches(item) ? card(item, kind, index) : null)}</div>{!items.some(matches) && <p className="rounded-xl border border-dashed p-8 text-center text-grayScale-500">{search ? "No matching content." : showLegacy ? "No archived courses." : `No ${collection[kind]} yet. Add your first ${kind} to get started.`}</p>}</section>
{chapterId && <section className="space-y-4 border-t pt-6"><div className="flex items-center justify-between"><h2 className="text-xl font-semibold">Chapter quizzes</h2><Button disabled={busy} onClick={() => openEditor({ kind: "quiz" })}><Plus size={16} className="mr-2" />Add quiz</Button></div><div className="grid gap-4 md:grid-cols-2">{quizzes.filter(matches).map(item => card(item, "quiz"))}</div>{!quizzes.some(matches) && <p className="text-grayScale-500">{search ? "No matching quizzes." : "No quizzes yet. Create a quiz, add its questions, then publish it."}</p>}</section>}
</>}
<Dialog open={!!editor} onOpenChange={open => { if (!open && !busy) setEditor(null) }}><DialogContent><DialogHeader><DialogTitle>{editor?.item ? "Edit" : "Add"} {editor?.kind}</DialogTitle></DialogHeader><form onSubmit={save} className="space-y-4"><label className="block space-y-2"><span>Title</span><Input autoFocus required value={form.name} onChange={event => setForm({ ...form, name: event.target.value })} /></label>
{editor?.kind !== "quiz" && <><label className="block space-y-2"><span>Description</span><Textarea value={form.description} onChange={event => setForm({ ...form, description: event.target.value })} /></label><label className="block space-y-2"><span>Thumbnail URL</span><Input type="url" value={form.thumbnail} onChange={event => setForm({ ...form, thumbnail: event.target.value })} /></label><label className="block space-y-2"><span>Access</span><select className="w-full rounded-md border p-2" value={form.access_tier} onChange={event => setForm({ ...form, access_tier: event.target.value })}><option value="FREE">Free</option><option value="PREMIUM">Premium</option></select></label></>}
{editor?.kind === "lesson" && <label className="block space-y-2"><span>Video URL</span><Input type="url" value={form.video_url} onChange={event => setForm({ ...form, video_url: event.target.value })} /></label>}
<div className="flex justify-end gap-2"><Button type="button" variant="outline" disabled={busy} onClick={() => setEditor(null)}>Cancel</Button><Button type="submit" disabled={busy || !form.name.trim()}>{busy ? "Saving…" : "Save"}</Button></div></form></DialogContent></Dialog>
<Dialog open={!!deleting} onOpenChange={open => { if (!open && !busy) setDeleting(null) }}><DialogContent><DialogHeader><DialogTitle>Delete {deleting?.kind}?</DialogTitle></DialogHeader><p>This removes “{deleting?.item.name ?? deleting?.item.title}” and its child content.</p><div className="flex justify-end gap-2"><Button variant="outline" disabled={busy} onClick={() => setDeleting(null)}>Cancel</Button><Button variant="destructive" disabled={busy} onClick={() => void remove()}>{busy ? "Deleting…" : "Delete"}</Button></div></DialogContent></Dialog>
</div>
}