import {useState, type ChangeEvent} from 'react'
import {SearchBar} from "../../../component/SearchBar.tsx";
import type {SearchParams} from "../../../../type/searchParams.ts";
import {PageSizeSelector} from "../../../component/pagination/PageSizeSelector.tsx";

interface BoardListSearchFormProps {
    totalCount: number
    searchParams: SearchParams
    onChange: (params: SearchParams) => void
}

const searchOptions = [
    {value: '0', label: '게시판명/연결메뉴'},
    {value: '1', label: '게시판유형'},
]

const pageSizeOptions = [
    {value: '10', label: '10건씩'},
    {value: '20', label: '20건씩'},
    {value: '30', label: '30건씩'},
]

export function BoardListSearchForm({
                                        totalCount,
                                        searchParams,
                                        onChange
                                    }: BoardListSearchFormProps) {
    const [draftParams, setDraftParams] = useState({
        searchSortCnd: searchParams.searchSortCnd,
        searchKeyword: searchParams.searchKeyword,
    });

    const handleChange = (
        name: string,
        value: string
    ) => {
        setDraftParams((prev) => ({
            ...prev,
            [name]: value,
        }));
    };

    const handleSearch = () => {
        onChange({
            ...searchParams,
            ...draftParams,
            pageIndex: 1,
        });
    };

    const handlePageChange = (event: ChangeEvent<HTMLSelectElement>) => {
        const {name, value} = event.target
        onChange({
            ...searchParams,
            [name]: Number(value),
            pageIndex: 1,
        })
    }

    return (
        <div className="search_area">
            <div className="search_left">
                <p className="total_number">
                    게시물 <b>{totalCount}</b>
                </p>
            </div>

            <div className="search_right">
                <SearchBar
                    searchSortCnd={draftParams.searchSortCnd}
                    searchKeyword={draftParams.searchKeyword}
                    options={searchOptions}
                    onChange={handleChange}
                    onSearch={handleSearch}
                />
                <PageSizeSelector
                    value={searchParams.pageUnit}
                    options={pageSizeOptions}
                    onChange={handlePageChange}
                />
            </div>
        </div>
    )
}
