import {useBoardListQuery} from "../hook/useBoardList.ts";
import {PageHeader} from "../../../component/PageHeader.tsx";
import {useEffect, useRef, useState} from "react";
import type {SearchParams} from "../../../../type/searchParams.ts";
import {BoardListSearchForm} from "../components/BoardListSearchForm.tsx";
import {BoardListTable} from "../components/BoardListTable.tsx";
import {toast} from "react-toastify";

const initSearchParam: SearchParams = {
    pageIndex: 1,
    pageUnit: 10,
    searchKeyword: "",
    searchSortCnd: "BBS_NM",
    searchSortOrd: "ASC"
}

export const BoardListPage = () => {
    const [searchParams, setSearchParams] = useState<SearchParams>(initSearchParam);
    const {
        list,
        totalCount,
        currentPage,
        recordPerPage,
        isLoading,
        error
    } = useBoardListQuery(searchParams);

    const toastId = useRef<string | number | null>(null);

    useEffect(() => {
        if (isLoading) {
            toastId.current = toast.info("Loading...");
        }

        if (!isLoading && toastId.current) {
            toast.dismiss(toastId.current);
            toast.success("로드 완료!");
        }

        if (error && toastId.current) {
            toast.dismiss(toastId.current);
            toast.error(error.message);
        }
    }, [isLoading, error]);

    const title = '게시판 관리'
    const breadcrumb = [{label: '게시판 관리'}]
    const homeUrl = '#'

    return (
        <>
            <PageHeader
                title={title}
                breadcrumb={breadcrumb}
                homeUrl={homeUrl}
            />
            <BoardListSearchForm
                totalCount={totalCount}
                searchParams={searchParams}
                onChange={setSearchParams}
            />
            {isLoading && <p>Loading...</p>}
            <BoardListTable
                items={list}
                params={searchParams}
                onChange={setSearchParams}
                totalCount={totalCount}
                currentPage={currentPage}
                recordPerPage={recordPerPage}
            />
        </>
    )
};
