import { useEffect, useState } from "react";
import { Button, Text, View } from "react-native";
import { sendTcpMessage } from "../lib/tcpScan";
import { type ZebraScanResult, zebraScanner } from "../lib/ZebraScanner";

const STX = "\x02";
const ETX = "\x03";

export function ScannerTestScreen() {
	const [lastResponse, setLastResponse] = useState("");

	const handleScan = async (scan: ZebraScanResult) => {
		console.log("Raw Zebra scan:", scan);

		const scanned = scan.data;

		let commandToSend = `${STX}98@${scanned}${ETX}`;

		// if we are sscc we need to scan like this .... <STX>98@]C100090087710038712256<ETX>
		if (scan.data.startsWith("000")) {
			commandToSend = `${STX}98@]C1${scanned}${ETX}`;
		}

		const something = await sendTcpMessage(commandToSend, "10.44.0.26", 50001);
		// Later this is where your TCP send goes.
		// const response = await sendTcpMessage(tcpMessage);

		console.log("TCP response:", something);
		setLastResponse(JSON.stringify(something));
	};

	useEffect(() => {
		zebraScanner.ensureProfile();
		zebraScanner.startListening();

		const sub = zebraScanner.addScanListener((scan) => {
			console.log("SCAN:", scan);
			handleScan(scan);
		});

		return () => {
			sub.remove();
			zebraScanner.stopListening();
		};
	}, []);

	return (
		<View style={{ padding: 20, gap: 12 }}>
			<Button
				title="Soft Trigger Scan"
				onPress={() => zebraScanner.triggerScan()}
			/>

			<Text>Waiting for scan...</Text>
			<Text>{lastResponse}</Text>
		</View>
	);
}
