import { type Dispatch, useActionState, useEffect, // useRef, useState, } from "react"; import { toast } from "react-toastify"; // import { useClickOutside } from "#/hooks/useClickOutside.ts"; import { useLichess } from "#/hooks/useLichess.ts"; import type { IUserStudyChapter } from "#/interfaces.ts"; import type { GameAction } from "#/reducers/gameReducer.ts"; interface IProps { selectedStudyId: string; gameDispatch: Dispatch; } type ChapterState = { status: "idle" | "success" | "error"; chapters: IUserStudyChapter[]; error: string | null; }; const initialChapterState: ChapterState = { status: "idle", chapters: [], error: null, }; const SelectStudyChapter = ({ selectedStudyId, gameDispatch }: IProps) => { const [isOpen, setIsOpen] = useState(false); const [search, setSearch] = useState(""); // const dropdownRef = useRef(null); const { getLichessStudyChapters, loadLichessStudyChapter } = useLichess(); const [chapterState, fetchChaptersAction, isPending] = useActionState( async (_prev: ChapterState, _formData: FormData): Promise => { if (!selectedStudyId) { return { status: "error", chapters: [], error: "No study selected.", } satisfies ChapterState; } const result = await getLichessStudyChapters({ studyId: selectedStudyId, }); console.log(result); if (result.ok) { return { status: "success", chapters: result.data, error: null, } satisfies ChapterState; } return { status: "error", chapters: [], error: result.error, } satisfies ChapterState; }, initialChapterState, ); const filteredChapters = chapterState.chapters.filter((chapter) => chapter.name.toLowerCase().includes(search.toLowerCase()), ); // useClickOutside({ isOpen, setIsOpen, setSearch, ref: dropdownRef }); useEffect(() => { if (isPending || chapterState.status === "success") { setIsOpen(true); } }, [isPending, chapterState.status]); const handleChapterClick = async (chapter: IUserStudyChapter) => { const { headers, pgn } = await loadLichessStudyChapter({ chapter }); gameDispatch({ type: "SET_GAME", payload: { pgn, headers } }); setIsOpen(false); setSearch(""); toast.success(`Loaded chapter "${chapter.name}"`); }; return (
{isOpen ? (
search setSearch(e.target.value)} className="w-full h-12 pl-10 pr-4 rounded-lg border border-(--neutral-content) text-(--base-content) placeholder-(--neutral-content)/50 outline-hidden transition-all duration-200 focus:border-(--accent) focus:outline-3 focus:outline-offset-2 focus:outline-(--accent)/50" />

{isPending ? (

Loading chapters…

) : filteredChapters.length > 0 ? (
    {filteredChapters.map((chapter) => (
  • ))}
) : (

No results found

)}
) : null}
); }; export default SelectStudyChapter;