import { useState, useRef, useCallback } from "react";
import { useIsomorphicEffect } from "../use-isomorphic-effect/use-isomorphic-effect.mjs";
const defaultOptions = {
  multiple: true,
  accept: "*"
};
function getInitialFilesList(files) {
  if (!files) {
    return null;
  }
  if (files instanceof FileList) {
    return files;
  }
  const result = new DataTransfer();
  for (const file of files) {
    result.items.add(file);
  }
  return result.files;
}
function createInput(options) {
  if (typeof document === "undefined") {
    return null;
  }
  const input = document.createElement("input");
  input.type = "file";
  if (options.accept) {
    input.accept = options.accept;
  }
  if (options.multiple) {
    input.multiple = options.multiple;
  }
  if (options.capture) {
    input.capture = options.capture;
  }
  if (options.directory) {
    input.webkitdirectory = options.directory;
  }
  input.style.display = "none";
  return input;
}
function useFileDialog(input = {}) {
  const options = { ...defaultOptions, ...input };
  const [files, setFiles] = useState(getInitialFilesList(options.initialFiles));
  const inputRef = useRef(null);
  const handleChange = useCallback(
    (event) => {
      var _a;
      const target = event.target;
      if (target == null ? void 0 : target.files) {
        setFiles(target.files);
        (_a = options.onChange) == null ? void 0 : _a.call(options, target.files);
      }
    },
    [options.onChange]
  );
  const createAndSetupInput = useCallback(() => {
    var _a;
    (_a = inputRef.current) == null ? void 0 : _a.remove();
    inputRef.current = createInput(options);
    if (inputRef.current) {
      inputRef.current.addEventListener("change", handleChange, { once: true });
      document.body.appendChild(inputRef.current);
    }
  }, [options, handleChange]);
  useIsomorphicEffect(() => {
    createAndSetupInput();
    return () => {
      var _a;
      return (_a = inputRef.current) == null ? void 0 : _a.remove();
    };
  }, []);
  const reset = useCallback(() => {
    var _a;
    setFiles(null);
    (_a = options.onChange) == null ? void 0 : _a.call(options, null);
  }, [options.onChange]);
  const open = useCallback(() => {
    var _a;
    if (options.resetOnOpen) {
      reset();
    }
    createAndSetupInput();
    (_a = inputRef.current) == null ? void 0 : _a.click();
  }, [options.resetOnOpen, reset, createAndSetupInput]);
  return { files, open, reset };
}
export {
  useFileDialog
};
