import { ColumnFilterElementTemplateOptions } from "primereact/column";
import { MultiSelect, MultiSelectChangeEvent, MultiSelectProps } from "primereact/multiselect";
import { DependencyList, useCallback } from "react";
import { useFilterAutoInit } from "./helpers";

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

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

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