import {useCallback, useRef, useState} from 'react';

type FieldType = string | number | boolean | string[];

export function useFilterField<T extends Record<string, FieldType>>(
  init: T,
): [T, (key: keyof T) => (value: FieldType) => void];
export function useFilterField<T extends Record<string, FieldType>>(
  init: T,
  reset: boolean,
): [
  T,
  {
    onChange: (key: keyof T) => (value: FieldType) => void;
    resetState: () => void;
  },
];
export function useFilterField<T extends Record<string, FieldType>>(
  init: T,
  reset?: boolean,
) {
  const [fields, setFields] = useState<T>(init);
  const memoInit = useRef(init);

  const onChange = useCallback(function (key: keyof T) {
    return function (value: FieldType) {
      setFields(prev => ({...prev, [key]: value}));
    };
  }, []);

  const resetState = useCallback(function () {
    setFields(memoInit.current);
  }, []);

  if (reset) {
    return [fields, {onChange, resetState}] as const;
  }

  return [fields, onChange] as const;
}
