import { ChangeEvent, ChangeEventHandler, useCallback, useState } from "react";

/** Track the value of the input without making the input controlled. */
export function useTrackedValue(
  onChange:
    | ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>
    | undefined
) {
  const [value, setValue] = useState<string | undefined>(undefined);

  const takeValueSnapshot = useCallback(
    (element: HTMLInputElement | HTMLTextAreaElement | null) =>
      setValue(element?.value),
    [setValue]
  );

  const handleChange = useCallback(
    (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
      setValue(event.target.value);
      onChange?.(event);
    },
    [setValue, onChange]
  );

  return [value, takeValueSnapshot, handleChange] as const;
}
