import { useCallback, useEffect, useState } from "react";
import { Text, View } from "react-native";
import { useAppStore } from "../hooks/useAppStore";
import { sendTcpMessage } from "../lib/tcpScan";
import { type ZebraScanResult, zebraScanner } from "../lib/ZebraScanner";
import { ScannedLabelBox } from "./ScannedLabels";

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

export default function ProdScanner() {
	const [lastScan, setLastScan] = useState<any>(null);
	const [tagScans, setTagScans] = useState<any>([]);
	const scannerIdFromStore = useAppStore((s) => s.scannerId);
	const serverIp = useAppStore((s) => s.serverIp);
	const serverPort = useAppStore((s) => s.serverPort);

	const handleScan = useCallback(
		async (scan: ZebraScanResult) => {
			const scanned = scan.data;

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

			// if we are sscc we need to scan like this .... <STX>98@]C100090087710038712256<ETX>
			if (scan.data.startsWith("000")) {
				commandToSend = `${STX}${scannerIdFromStore}@]C1${scanned}${ETX}`;
				setTagScans((prev: any) => [
					parseInt(scanned.slice(10, -1) || "000", 10).toString(),
					...prev,
				]);
			}

			// if we change commands we want to zero out the last scanned labels
			if (/^[a-zA-Z]/.test(scan.data)) {
				setTagScans([]);
			}

			const something = await sendTcpMessage(
				commandToSend,
				serverIp,
				parseInt(serverPort || "0", 10),
			);
			// Later this is where your TCP send goes.
			// const response = await sendTcpMessage(tcpMessage);
			setLastScan(something.data[0]);
			//console.log("TCP response:", something);
		},
		[scannerIdFromStore, serverIp, serverPort],
	);

	console.log(lastScan);

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

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

		return () => {
			sub.remove();
			zebraScanner.stopListening();
		};
	}, [handleScan]);
	return (
		<View>
			<View>
				<View style={{ alignItems: "center", margin: 10 }}>
					<Text style={{ fontSize: 20, fontWeight: "600" }}>
						Scanner ID: {parseInt(scannerIdFromStore || "0", 10)}
					</Text>
				</View>
				{!lastScan ? (
					<View
						style={{
							marginTop: 10,
							alignItems: "center",
						}}
					>
						<Text className="text-xl font-bold">Waiting on scan....</Text>
					</View>
				) : (
					<View
						style={{
							marginTop: 10,
							alignItems: "center",
						}}
					>
						<Text style={{ fontSize: 20, fontWeight: "600" }}>
							{lastScan?.action}
						</Text>

						{lastScan?.type === "error" ? (
							<Text style={{ fontSize: 20, fontWeight: "600" }}>
								{lastScan?.message}
							</Text>
						) : (
							<View
								style={{
									marginTop: 15,
									alignItems: "center",
								}}
							>
								<Text style={{ fontSize: 20, fontWeight: "600" }}>
									{lastScan?.prompt}
								</Text>
								<Text style={{ fontSize: 20, fontWeight: "600" }}>
									{lastScan?.message}
								</Text>
							</View>
						)}
					</View>
				)}
			</View>

			<ScannedLabelBox labels={tagScans} />
		</View>
	);
}
