import { useEffect, useState } from "react";
import { Button, Text, View } from "react-native";
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;

		// Hard-coded command example:
		// <stx>98@{scanned}<etx>
		const tcpMessage = `${STX}98@${scanned}${ETX}`;

		console.log("TCP message to send:", tcpMessage);
		console.log("TCP message visible:", `<stx>98@${scanned}<etx>`);

		// Later this is where your TCP send goes.
		// const response = await sendTcpMessage(tcpMessage);

		const fakeResponse = `Would send TCP: <stx>98@${scanned}<etx>`;

		console.log("TCP response:", fakeResponse);
		setLastResponse(fakeResponse);
	};

	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>
	);
}
