import SwitchCameraOutlined from "@mui/icons-material/SwitchCameraOutlined";
import { Box, IconButton, type SxProps } from "@mui/material";
import { getLocalizedString } from "@olenbetong/appframe-core";
import type BarcodeReaderType from "dynamsoft-javascript-barcode";
import { useRef } from "react";
import { ErrorIcon } from "./Error";
import { useScanner } from "./useScanner";

declare global {
	interface Window {
		BarcodeReader: typeof BarcodeReaderType;
	}
}

export type BarcodeScannerProps = {
	onRead: (barcode: string) => void;
};

const frameSx: SxProps = {
	position: "absolute",
	bottom: 0,
	left: 0,
	right: 0,
	top: 0,
	height: "100%",
	width: "100%",
};

export function BarcodeScanner({ onRead }: BarcodeScannerProps) {
	let readerRoot = useRef<HTMLElement | null>(null);
	let canvas = useRef<HTMLCanvasElement | null>(null);
	let { devices, error, setNextDevice } = useScanner(readerRoot, canvas, onRead);

	return (
		<Box
			sx={{
				position: "relative",
				bgcolor: "black",
				height: "100%",
			}}
		>
			<Box sx={{ height: "100%" }} ref={readerRoot}>
				<Box component="video" className="dbrScanner-video" playsInline sx={frameSx} />
				<Box component="canvas" sx={frameSx} width="1280" height="720" ref={canvas} />
				{error && <ErrorIcon {...error} />}
			</Box>
			<Box
				sx={{
					display: "flex",
					alignItems: "center",
					justifyContent: "space-between",
					position: "absolute",
					bottom: 0,
					left: 0,
					right: 0,
					py: 1,
					px: 3,
					color: "white",
				}}
			>
				{devices.length <= 1 && <span />}
				{devices.length > 1 && (
					<IconButton
						color="inherit"
						aria-label={getLocalizedString("Switch camera")}
						onClick={() => setNextDevice()}
						size="large"
					>
						<SwitchCameraOutlined />
					</IconButton>
				)}
			</Box>
		</Box>
	);
}
