import Constants from "expo-constants";
import { useRouter } from "expo-router";
import { useState } from "react";
import { Alert, Button, Text, TextInput, View } from "react-native";
import Toast from "react-native-toast-message";
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);

	// TODO: if on lst version and the user is manager or admin just login

	const authCheck = () => {
		if (pin === "6971") {
			setAuth(true);
		} else {
			//Alert.alert("Incorrect pin entered please try again");
			Toast.show({
				type: "error",
				text1: "Incorrect pin entered please try again",
			});
			setPin("");
		}
	};

	const handleSave = async () => {
		if (!serverIp.trim() || !serverPort.trim()) {
			//Alert.alert("Missing info", "Please fill in both fields.");
			Toast.show({
				type: "error",
				text1: "Missing info",
				text2: "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.");
		Toast.show({
			type: "info",
			text1: "Saved",
			text2: "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,
							gap: 3,
						}}
					>
						<Button title="Submit" onPress={authCheck} />
						<Button
							title="Home"
							onPress={() => {
								router.push("/(tabs)/scanner");
							}}
						/>
					</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 className="flex gap-2 flex-row">
						<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: 50,
				}}
			>
				<Text className="text-sm color-[#312f2f]">
					App v{version}-{build}
				</Text>
				<Text className="text-sm color-[#312f2f]">
					Server version - v{server?.versionName}-{server?.versionCode}
				</Text>
			</View>
		</View>
	);
}
