import axios from "axios";
import Constants from "expo-constants";
import { Redirect, useRouter } from "expo-router";
import { useEffect, useState } from "react";
import { ActivityIndicator, Text, View } from "react-native";
import { useAppStore } from "../hooks/useAppStore";
import { useMobileAuthStore } from "../hooks/useMobileAuth";
import { useServerStore } from "../hooks/useServerCheck";
import { devDelay } from "../lib/devMode";

export default function Index() {
	const router = useRouter();
	const [message, setMessage] = useState(<Text>Starting app...</Text>);
	const [ready, setReady] = useState(false);
	const setServerVersion = useServerStore((s) => s.setServerVersion);
	//const { isUnlocked } = useMobileAuthStore();

	const hasHydrated = useAppStore((s) => s.hasHydrated);
	const serverPort = useAppStore((s) => s.serverPort);
	const serverIp = useAppStore((s) => s.serverIp);
	const build = Constants.expoConfig?.android?.versionCode ?? 1;
	const hasValidSetup = useAppStore((s) => s.hasValidSetup);

	useEffect(() => {
		if (!hasHydrated) {
			setMessage(<Text>Loading app...</Text>);
			return;
		}

		const startup = async () => {
			try {
				await devDelay(1500);

				setMessage(<Text>Validating data...</Text>);
				await devDelay(1500);

				if (!hasValidSetup()) {
					router.replace("/setup");
					return;
				}

				// checking for lst.
				console.log(
					`http://${serverIp}:${parseInt(serverPort || "0", 10) >= 50000 ? "3000" : serverPort}/lst/api/mobile/version`,
				);
				try {
					const res = await axios.get(
						`http://${serverIp}:${parseInt(serverPort || "0", 10) >= 50000 ? "3000" : serverPort}/lst/api/mobile/version`,
						{
							timeout: 5000,
						},
					);

					console.log(res.data);

					// if the build version dose not match the latest server version force update
					if (res.status === 200) {
						setServerVersion(res.data);
					}

					// TODO: change the header to show orange and theres a new version
					// console.log(build < res.data.minSupportedVersionCode);
					// if (build < res.data.minSupportedVersionCode) {
					// 	router.replace("/updateScreen");
					// 	return;
					// }
				} catch (error) {
					console.log("Error: ", error);
				}

				setMessage(<Text>Checking scanner mode...</Text>);
				await devDelay(1500);

				if (parseInt(serverPort || "0", 10) >= 50000) {
					setMessage(
						<Text>
							Starting normal alplaprod scanner that has no LST rules
						</Text>,
					);
					await devDelay(1500);
					//router.replace("/scanner");
					setReady(true);
					return;
				}

				setMessage(<Text>Checking for updates</Text>);
				await devDelay(1500);
				// TODO if theres an update go to update screen message :D
				setMessage(<Text>Opening LST scan app</Text>);
				await devDelay(3250);

				setReady(true);
			} catch (error) {
				console.log("Startup error", error);
				setMessage(<Text>Something went wrong during startup.</Text>);
			}
		};

		startup();
	}, [
		hasHydrated,
		hasValidSetup,
		serverPort,
		serverIp,
		router,
		setServerVersion,
	]);

	// if (ready && !isUnlocked) {
	// 	return <Redirect href={"/login"} />;
	// }
	if (ready) {
		return <Redirect href="/(tabs)/scanner" />;
	}
	return (
		<View
			style={{
				flex: 1,
				justifyContent: "center",
				alignItems: "center",
				marginTop: 12,
			}}
		>
			{message}
			<ActivityIndicator size="large" />
		</View>
	);
}
