import { Icon } from "./Icon/Icon.js";
import { InputSubtext, inputBlockStyle } from "../styles/fields.js";
import { Pill } from "./Pill.js";
import styled from "@emotion/styled";
import { Fragment, useRef, useState } from "react";
import { jsx, jsxs } from "@emotion/react/jsx-runtime";
//#region src/components/FileInput.tsx
function FileInput({ name, onChange, filePurpose = "", onRemoveFile }) {
	const [fileName, setFileName] = useState();
	const [fileContent, setFileContent] = useState();
	const [fileErrorMsg, setFileErrorMsg] = useState();
	const fileInputRef = useRef(null);
	const handleChange = (changeEvent) => {
		const file = changeEvent.target.files?.[0];
		if (!file) return;
		const reader = new FileReader();
		reader.onload = (readEvent) => {
			let fileContent = readEvent?.target?.result;
			setFileName(file.name);
			if (!fileContent) {
				setFileErrorMsg("Unable to read file");
				return;
			}
			if (typeof fileContent !== "string") fileContent = new TextDecoder().decode(fileContent);
			setFileErrorMsg(void 0);
			setFileContent(fileContent);
			onChange(fileContent);
		};
		reader.readAsText(file);
	};
	function handleRemoveFile() {
		if (fileInputRef.current) fileInputRef.current.value = "";
		setFileName(void 0);
		setFileContent(void 0);
		setFileErrorMsg(void 0);
		onRemoveFile();
	}
	return /* @__PURE__ */ jsxs(StyledFileInputContainer, { children: [/* @__PURE__ */ jsxs(StyledFileInput, {
		hasValidFileSet: Boolean(fileName && fileContent),
		children: [/* @__PURE__ */ jsx("label", {
			htmlFor: name,
			children: fileName && fileContent ? /* @__PURE__ */ jsx(Pill, {
				text: fileName,
				cursor: "pointer",
				onDeleteMouseDown: handleRemoveFile,
				onDeleteFromKeyboard: handleRemoveFile
			}) : /* @__PURE__ */ jsxs(Fragment, { children: [
				/* @__PURE__ */ jsx(Icon, {
					name: "Upload",
					width: 26,
					tutorialStep: 6
				}),
				"Upload ",
				filePurpose || "",
				" file"
			] })
		}), /* @__PURE__ */ jsx("input", {
			type: "file",
			id: name,
			onChange: handleChange,
			ref: fileInputRef
		})]
	}), fileErrorMsg ? /* @__PURE__ */ jsx(InputSubtext, {
		text: fileErrorMsg,
		hasError: true
	}) : null] });
}
const StyledFileInputContainer = styled.div``;
const StyledFileInput = styled.div`
  input[type="file"] {
    display: none;
  }

  label {
    display: block;
    cursor: pointer;
    ${({ theme, hasValidFileSet }) => inputBlockStyle({
	theme,
	hasValue: hasValidFileSet,
	hasError: false
})}
  }
`;
//#endregion
export { FileInput, StyledFileInput };
