// app/config.tsx

import Constants from "expo-constants";
import { useRouter } from "expo-router";
import { useEffect, useState } from "react";
import { Alert, Button, Text, TextInput, View } from "react-native";

export default function Config() {
	const [serverUrl, setServerUrl] = useState("");
	const [scannerId, setScannerId] = useState("");
	const [config, setConfig] = useState<AppConfig | null>(null);
	const [loading, setLoading] = useState(true);
	const router = useRouter();

	const version = Constants.expoConfig?.version;
	const build = Constants.expoConfig?.android?.versionCode ?? 1;

	useEffect(() => {
		const loadConfig = async () => {
			const existing = await getConfig();

			if (existing) {
				setServerUrl(existing.serverUrl);
				setScannerId(existing.scannerId);
				setConfig(existing);
			}

			setLoading(false);
		};

		loadConfig();
	}, []);

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

		await saveConfig({
			serverUrl: serverUrl.trim(),
			scannerId: scannerId.trim(),
		});

		Alert.alert("Saved", "Config saved to device.");
		//router.replace("/");
	};

	if (loading) {
		return <Text>Loading config...</Text>;
	}

	return (
		<View style={{ flex: 1, padding: 16, gap: 12 }}>
			<View style={{ alignItems: "center", margin: 10 }}>
				<Text style={{ fontSize: 20, fontWeight: "600" }}>
					LST Scanner Config
				</Text>
			</View>

			<Text>Server IP</Text>
			<TextInput
				value={serverUrl}
				onChangeText={setServerUrl}
				placeholder="192.168.1.1"
				autoCapitalize="none"
				keyboardType="numeric"
				style={{ borderWidth: 1, padding: 10, borderRadius: 8 }}
			/>

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

			<View
				style={{ flexDirection: "row", justifyContent: "center", padding: 3 }}
			>
				<Button title="Save Config" onPress={handleSave} />
			</View>

			<View style={{ marginTop: "auto", alignItems: "center", padding: 10 }}>
				<Text style={{ fontSize: 12, color: "#666" }}>
					LST Scanner v{version}-{build}
				</Text>
			</View>
		</View>
	);
}
