import { memo, useCallback, useRef } from "react";

/**
 *
 * @type {React.FC <{
 *    children: Function;
 *    onChange?: React.ChangeEventHandler<HTMLInputElement>;
 * }>}
 * @returns
 */
const Component = (props) => {
  const inputRef = useRef(null);

  const onClick = useCallback(() => {
    inputRef.current.click();
  }, [inputRef]);

  return (
    <>
      <input
        type="file"
        onChange={(e) => {
          const files = Array.from(e.target.files);
          if (props.onChange && typeof props.onChange === "function")
            props.onChange(files, e);

          e.target.value = null; // Reset the input value to allow re-uploading the same file
        }}
        ref={inputRef}
        style={{ display: "none" }}
        multiple
      />
      {props.children(inputRef, onClick)}
    </>
  );
};

const InputFileHidden = memo(Component);
export default InputFileHidden;
