import { Redirect, useRouter } from "expo-router";
import { useEffect, useState } from "react";
import { ActivityIndicator, Text, View } from "react-native";
import { useAppStore } from "../hooks/useAppStore";
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 hasHydrated = useAppStore((s) => s.hasHydrated);
	const serverPort = useAppStore((s) => s.serverPort);
	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;
				}

				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);
				//router.replace("/scanner");
				setReady(true)
			} catch (error) {
				console.log("Startup error", error);
				setMessage(<Text>Something went wrong during startup.</Text>);
			}
		};

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

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