import type {ChangeEvent} from 'react'
import {SearchBar} from "./SearchBar.tsx";
import type {SearchParams} from "../../type/searchParams.ts";
import {PageSizeSelector} from "./pagination/PageSizeSelector.tsx";
import type {SearchModel} from "../../type/viewModel.ts";

interface ListSearchFormProps<T extends SearchParams> extends SearchModel<T> {
    totalLabel?: string;
}

export function ListSearchForm<T extends SearchParams>({
                                                           totalItems,
                                                           searchParams,
                                                           onChange,
                                                           searchOptions,
                                                           pageSizeOptions,
                                                           totalLabel,

                                                       }: ListSearchFormProps<T>) {
    const handleChange = (
        name: string,
        value: string
    ) => {
        onChange({
            ...searchParams,
            [name]: value,
            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">
                    {totalLabel} <b>{totalItems}</b>건
                </p>
            </div>

            <div className="search_right">
                <SearchBar
                    searchCnd={searchParams.searchCnd}
                    searchKeyword={searchParams.searchKeyword}
                    options={searchOptions}
                    onChange={handleChange}
                />
                {
                    pageSizeOptions && pageSizeOptions.length > 0 && (
                        <PageSizeSelector
                            value={searchParams.pageUnit}
                            options={pageSizeOptions}
                            onChange={handlePageChange}
                        />
                    )
                }
            </div>
        </div>
    )
}
