import {useParams} from "react-router-dom";
import {useBoardArticleList} from "../hook/useBoardArticleList.ts";
import type {BoardArticleSearchParams} from "../type/board.types.ts";
import {useState} from "react";
import {PageHeader} from "../../../component/PageHeader.tsx";
import {ListSearchForm} from "../../../component/ListSearchForm.tsx";
import {Pagination} from "../../../component/pagination/Pagination.tsx";
import {useLoadingToast} from "../../../hook/useLoadingToast.ts";
import {BoartArticleListTable} from "../components/article/BoardArticleListTable.tsx";
import {BoardArticleImageListTable} from "../components/article/BoardArticleImageListTable.tsx";

const initSearchParam: BoardArticleSearchParams = {
    pageIndex: 1,
    pageUnit: 10,
    searchCnd: "0",
    searchKeyword: "",
    searchSortCnd: "FRST_REGIST_PNTTM",
    searchSortOrd: "ASC",
    bbsId: ""
};

export const BoardArticleListPage = () => {
    const {bbsId = ''} = useParams();
    const searchOptions = [
        {value: '0', label: '제목'},
        {value: '1', label: '내용'},
        {value: '2', label: '작성자'},
    ]

    const [searchParams, setSearchParams] = useState<BoardArticleSearchParams>({
        ...initSearchParam,
        bbsId,
    });
    const {
        list,
        extraData,
        totalItems,
        currentPage,
        totalPages,
        size,
        isLoading,
        error
    } = useBoardArticleList(searchParams);

    const bbsNm = extraData ? extraData.boardMaster?.bbsNm : null;
    const bbsTyCode = extraData ? extraData.boardMaster?.bbsTyCode : null;
    useLoadingToast({
        isLoading,
        error,
        successMessage: `${bbsNm} 목록을 불러왔습니다.`
    });

    const title = `${bbsNm} 목록`
    const breadcrumb = [{label: '게시판 관리', url: '/admin/cop/bbs/SelectBBSMasterInfs.do'}, {label: `${bbsNm} 목록`}]
    const homeUrl = '#'

    return (
        <>
            <PageHeader title={title} breadcrumb={breadcrumb} homeUrl={homeUrl}/>
            <ListSearchForm
                totalItems={totalItems}
                searchParams={searchParams}
                onChange={setSearchParams}
                searchOptions={searchOptions}
                totalLabel={"게시글"}
            />
            {bbsTyCode === "BBST05" ?
                <BoardArticleImageListTable
                    items={list}
                /> :
                <BoartArticleListTable
                    items={list}
                    params={searchParams}
                    onChange={setSearchParams}
                    totalPages={totalPages}
                    currentPage={currentPage}
                    totalItems={totalItems}
                />
            }
            <Pagination
                totalItems={totalItems}
                totalPages={totalPages}
                currentPage={currentPage}
                size={size}
                onPageChange={() => {
                }}
            />
        </>
    );
}