import Constants from "expo-constants";
import { useRouter } from "expo-router";
import { useState } from "react";
import { Alert, Button, Text, TextInput, View } from "react-native";
import { useAppStore } from "../hooks/useAppStore";
import { useServerStore } from "../hooks/useServerCheck";

export default function Setup() {
	const router = useRouter();
	const [auth, setAuth] = useState(false);
	const [pin, setPin] = useState("");
	const version = Constants.expoConfig?.version;
	const build = Constants.expoConfig?.android?.versionCode ?? 1;

	const serverIpFromStore = useAppStore((s) => s.serverIp);
	const serverPortFromStore = useAppStore((s) => s.serverPort);
	const scannerIdFromStore = useAppStore((s) => s.scannerId);

	const updateAppState = useAppStore((s) => s.updateAppState);

	// local form state
	const [serverIp, setLocalServerIp] = useState(serverIpFromStore);
	const [serverPort, setLocalServerPort] = useState(serverPortFromStore);
	const [scannerId, setScannerId] = useState(scannerIdFromStore);

	const server = useServerStore((s) => s.serverVersion);

	const authCheck = () => {
		if (pin === "6971") {
			setAuth(true);
		} else {
			Alert.alert("Incorrect pin entered please try again");
			setPin("");
		}
	};

	const handleSave = async () => {
		if (!serverIp.trim() || !serverPort.trim()) {
			Alert.alert("Missing info", "Please fill in both fields.");
			return;
		}

		updateAppState({
			serverIp: serverIp.trim(),
			serverPort: serverPort.trim(),
			scannerId: scannerId?.trim(),
			setupCompleted: true,
			isRegistered: true,
		});

		Alert.alert("Saved", "Config saved to device.");
		//router.replace("/");
	};
	return (
		<View
			style={{
				flex: 1,
				//justifyContent: "center",
				alignItems: "center",
				marginTop: 50,
			}}
		>
			<View style={{ alignItems: "center", margin: 10 }}>
				<Text style={{ fontSize: 20, fontWeight: "600" }}>
					LST Scanner Config
				</Text>
			</View>
			{!auth ? (
				<View>
					<Text>Pin Number</Text>
					<TextInput
						value={pin}
						onChangeText={setPin}
						placeholder=""
						//autoCapitalize="none"
						keyboardType="numeric"
						style={{ borderWidth: 1, padding: 10, borderRadius: 8, width: 128 }}
					/>
					<View
						style={{
							flexDirection: "row",
							justifyContent: "center",
							padding: 3,
							borderRadius: 8,
						}}
					>
						<Button title="Submit" onPress={authCheck} />
					</View>
				</View>
			) : (
				<View>
					<Text>Server IP</Text>
					<TextInput
						value={serverIp}
						onChangeText={setLocalServerIp}
						placeholder="192.168.1.1"
						//autoCapitalize="none"
						keyboardType="numeric"
						style={{ borderWidth: 1, padding: 10, borderRadius: 8 }}
					/>

					<Text>Server port</Text>
					<TextInput
						value={serverPort}
						onChangeText={setLocalServerPort}
						placeholder="3000"
						//autoCapitalize="characters"
						keyboardType="numeric"
						style={{ borderWidth: 1, padding: 10, borderRadius: 8 }}
					/>

					{parseInt(serverPort ?? "0", 10) >= 50000 && (
						<View>
							<Text>Scanner ID</Text>
							<Text style={{ width: 250 }}>
								The ID is required to be able to scan. The scanner will be
								treated as a normal scanner direct to alplaprod. no extra rules
								added.
							</Text>
							<TextInput
								value={scannerId}
								onChangeText={setScannerId}
								placeholder="0001"
								autoCapitalize="characters"
								keyboardType="numeric"
								style={{ borderWidth: 1, padding: 10, borderRadius: 8 }}
							/>
						</View>
					)}

					<View
						style={{
							flexDirection: "row",
							justifyContent: "center",
							padding: 3,
							gap: 3,
						}}
					>
						<Button title="Save Config" onPress={handleSave} />
						<Button
							title="Home"
							onPress={() => {
								router.push("/(tabs)/scanner");
							}}
						/>
					</View>
				</View>
			)}
			<View
				style={{
					marginTop: "auto",
					alignItems: "center",
					padding: 10,
					marginBottom: 12,
				}}
			>
				<Text className="text-[12] color-#666">
					App v{version}-{build}
				</Text>
				<Text className="text-[12] color-#666">
					Server version - v{server?.versionName}-{server?.versionCode}
				</Text>
			</View>
		</View>
	);
}
