import "./index.css";

import { Box, Button } from "@mui/material";
import { getLocalizedString } from "@olenbetong/appframe-core";

import { useEffect, useRef, useState } from "react";

import { useHIDScanner } from "./useHIDScanner";

export function AddElementHIDScanner({ onScan }: { onScan: (id: string) => void }) {
	let [enabled, setEnabled] = useState(false);
	let root = useRef<HTMLDivElement>(null);

	useEffect(() => {
		if (!root.current) return;

		let rootElem = root.current;

		function handleFocus() {
			setEnabled(true);
		}

		function handleBlur() {
			setEnabled(false);
		}

		rootElem.addEventListener("focus", handleFocus);
		rootElem.addEventListener("blur", handleBlur);
		rootElem.focus();

		return () => {
			rootElem.removeEventListener("focus", handleFocus);
			rootElem.removeEventListener("blur", handleBlur);
		};
	}, []);

	useHIDScanner(onScan, enabled);

	return (
		<Box
			sx={{
				height: "100%",
				bgcolor: "#ddd",
				display: "flex",
				alignItems: "center",
				justifyContent: "center",
				backgroundImage: enabled ? "linear-gradient(var(--angle), #777, #bbb, #777)" : "none",
				animation: enabled ? "MovingBackground 8s linear infinite" : "none",
			}}
			tabIndex={0}
			ref={root}
		>
			{enabled ? (
				<span>{getLocalizedString("Listening for scanned elements")}...</span>
			) : (
				<Button
					variant="contained"
					onClick={() => {
						if (root.current) root.current.focus();
					}}
				>
					{getLocalizedString("Start listening")}
				</Button>
			)}
		</Box>
	);
}
