import { useCallback, useEffect, useMemo, useState } from "react" import { Library, Search } from "lucide-react" import { toast } from "sonner" import { getQuestions } from "../../../../api/courses.api" import { SearchHighlight } from "../../../../components/SearchHighlight" import { Button } from "../../../../components/ui/button" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "../../../../components/ui/dialog" import { Input } from "../../../../components/ui/input" import { getApiErrorMessage } from "../../../../lib/apiErrors" import { buildQuestionBankSearchHaystack, getQuestionBankListLabels, matchesQuestionBankHaystack, normalizeQuestionBankItem, type QuestionBankListLabels, } from "../../../../lib/questionBankDisplay" import type { QuestionDetail } from "../../../../types/course.types" import type { QuestionTypeDefinition } from "../../../../types/questionTypeDefinition.types" import { cn } from "../../../../lib/utils" const BANK_CACHE_TTL_MS = 5 * 60 * 1000 const BANK_PAGE_SIZE = 200 let bankCache: { fetchedAt: number; questions: QuestionDetail[] } | null = null let bankFetchInFlight: Promise | null = null function unwrapQuestionsPayload(payload: unknown): unknown[] { if (Array.isArray(payload)) return payload if ( payload && typeof payload === "object" && Array.isArray((payload as { questions?: unknown[] }).questions) ) { return (payload as { questions: unknown[] }).questions } if ( payload && typeof payload === "object" && Array.isArray((payload as { Questions?: unknown[] }).Questions) ) { return (payload as { Questions: unknown[] }).Questions } return [] } function readChunkTotal(payload: unknown, metaTotal?: number): number | undefined { if (typeof metaTotal === "number" && Number.isFinite(metaTotal)) return metaTotal if (!payload || typeof payload !== "object" || Array.isArray(payload)) return undefined const record = payload as Record const direct = Number(record.total_count ?? record.TotalCount) if (Number.isFinite(direct)) return direct return undefined } async function fetchAllBankQuestions(): Promise { const firstRes = await getQuestions({ limit: BANK_PAGE_SIZE, offset: 0 }) const firstPayload = firstRes.data?.data as unknown const firstMeta = firstRes.data?.metadata as { total_count?: number } | null | undefined const firstRaw = unwrapQuestionsPayload(firstPayload) const firstChunk = firstRaw .map((row) => normalizeQuestionBankItem(row)) .filter((row): row is QuestionDetail => row != null) const total = readChunkTotal(firstPayload, firstMeta?.total_count) ?? firstChunk.length if (firstRaw.length < BANK_PAGE_SIZE || firstChunk.length >= total) { return firstChunk } const offsets: number[] = [] for (let offset = BANK_PAGE_SIZE; offset < total; offset += BANK_PAGE_SIZE) { offsets.push(offset) } const pages = await Promise.all( offsets.map(async (offset) => { const res = await getQuestions({ limit: BANK_PAGE_SIZE, offset }) const payload = res.data?.data as unknown return unwrapQuestionsPayload(payload) .map((row) => normalizeQuestionBankItem(row)) .filter((row): row is QuestionDetail => row != null) }), ) return [...firstChunk, ...pages.flat()] } async function loadQuestionBank(options?: { force?: boolean }): Promise { const now = Date.now() if ( !options?.force && bankCache && now - bankCache.fetchedAt < BANK_CACHE_TTL_MS ) { return bankCache.questions } if (bankFetchInFlight) return bankFetchInFlight bankFetchInFlight = fetchAllBankQuestions() .then((questions) => { bankCache = { fetchedAt: Date.now(), questions } return questions }) .finally(() => { bankFetchInFlight = null }) return bankFetchInFlight } interface BankListRow { question: QuestionDetail labels: QuestionBankListLabels haystack: string } interface QuestionBankAttachDialogProps { open: boolean onOpenChange: (open: boolean) => void /** Question IDs already on this practice — hidden from selection. */ excludeIds: number[] onAttach: (questions: QuestionDetail[]) => void typeDefinitions?: QuestionTypeDefinition[] } export function QuestionBankAttachDialog({ open, onOpenChange, excludeIds, onAttach, typeDefinitions = [], }: QuestionBankAttachDialogProps) { const [loading, setLoading] = useState(false) const [attaching, setAttaching] = useState(false) const [questions, setQuestions] = useState( () => bankCache?.questions ?? [], ) const [searchQuery, setSearchQuery] = useState("") const [selectedIds, setSelectedIds] = useState([]) const excluded = useMemo(() => new Set(excludeIds.filter((id) => id > 0)), [excludeIds]) const hydrateBank = useCallback(async () => { const hasWarmCache = bankCache != null && Date.now() - bankCache.fetchedAt < BANK_CACHE_TTL_MS if (hasWarmCache && bankCache) { setQuestions(bankCache.questions) setLoading(false) return } setLoading(!(bankCache && bankCache.questions.length > 0)) try { const rows = await loadQuestionBank() setQuestions(rows) } catch (error) { console.error("Failed to load question bank:", error) toast.error("Could not load question bank", { description: getApiErrorMessage(error, "Try again in a moment."), }) if (!bankCache?.questions.length) setQuestions([]) } finally { setLoading(false) } }, []) useEffect(() => { if (!open) return setSearchQuery("") setSelectedIds([]) void hydrateBank() }, [open, hydrateBank]) /** Client-side index: load once from API, filter locally as the user types. */ const searchableRows = useMemo((): BankListRow[] => { return questions .filter((q) => !excluded.has(q.id)) .map((question) => ({ question, labels: getQuestionBankListLabels(question, typeDefinitions), haystack: buildQuestionBankSearchHaystack(question, typeDefinitions), })) }, [questions, excluded, typeDefinitions]) const filtered = useMemo(() => { return searchableRows.filter((row) => matchesQuestionBankHaystack(row.haystack, searchQuery), ) }, [searchableRows, searchQuery]) const toggleId = (id: number) => { setSelectedIds((prev) => prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id], ) } const handleAttach = () => { if (selectedIds.length === 0) return setAttaching(true) try { const byId = new Map(questions.map((q) => [q.id, q])) const details = selectedIds .map((id) => byId.get(id)) .filter((q): q is QuestionDetail => q != null) if (details.length === 0) { throw new Error("Could not resolve the selected questions") } onAttach(details) onOpenChange(false) } catch (error) { toast.error("Could not attach questions", { description: getApiErrorMessage(error, "Try again."), }) } finally { setAttaching(false) } } return ( Attach from question bank Pick existing questions to include in this practice. Search filters this list on your device — matching words are highlighted as you type.
setSearchQuery(e.target.value)} placeholder="Type to filter by question text, type, or difficulty…" className="h-10 rounded-xl border-grayScale-200 pl-9" autoFocus />

{selectedIds.length > 0 ? `${selectedIds.length} selected` : loading ? "Loading…" : searchQuery.trim() ? `${filtered.length} of ${searchableRows.length} match` : `${filtered.length} available`}

{loading ? (

Loading question bank…

) : filtered.length === 0 ? (

No matching questions in the bank.

) : (
    {filtered.map(({ question: q, labels }) => { const checked = selectedIds.includes(q.id) return (
  • ) })}
)}
) }