import { ColumnFilterElementTemplateOptions } from "primereact/column";
import { Dropdown, DropdownChangeEvent, DropdownProps } from "primereact/dropdown";
import { DependencyList, useCallback } from "react";
import { useFilterAutoInit } from "./helpers";

interface DropdownFilterConfig extends Partial<DropdownProps> {
    afterFilter?: (value: any) => void;
}

export function useDropdownFilter(items: DropdownFilterConfig | any[], deps?: DependencyList): ((options: ColumnFilterElementTemplateOptions) => React.ReactNode) {
    let config: DropdownFilterConfig = {};
    if (Array.isArray(items)) {
        config.options = items;
    } else {
        config = items;
    }

    return useCallback((options: ColumnFilterElementTemplateOptions) => {

        useFilterAutoInit(options.field);
        return (<Dropdown
            value={options.value}
            onChange={(e: DropdownChangeEvent) => {
                options.filterApplyCallback(e.value);
                config?.afterFilter?.(e.value);
            }}
            loading={config.options == undefined}
            optionLabel="label"
            placeholder={`Filter`}
            className="p-column-filter"
            checkmark
            {...config}
        />)
    }, deps ?? []);
}