import { ColumnFilterElementTemplateOptions } from "primereact/column";
import { InputText, InputTextProps } from "primereact/inputtext";
import { DependencyList, useCallback, useEffect } from "react";
import { useFilterAutoInit } from "./helpers";

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

export function useTextFilter(
  config?: TextFilterConfig,
  deps?: DependencyList,
): (options: ColumnFilterElementTemplateOptions) => React.ReactNode {
  return useCallback((options: ColumnFilterElementTemplateOptions) => {
    
    useFilterAutoInit(options.field);

    const externalValue = config?.value;
    useEffect(() => {
      if (externalValue !== undefined) {
        options.filterApplyCallback(externalValue);
      }
    }, [externalValue]);

    return (
      <InputText
        {...config}
        value={options.value ?? ""}
        onChange={(e) => {
          options.filterApplyCallback(e.target.value);
          config?.afterFilter?.(e.target.value);
        }}
        placeholder="Filter"
        className="p-column-filter"
      />
    );
  }, deps ?? []);
}
