import axios from "axios";
import Constants from "expo-constants";
import { useEffect, useRef, useState } from "react";
import { setApiConfig } from "../lib/apiHelper";
import { devDelay } from "../lib/devMode";
import { versionCheck } from "../lib/versionValidation";
import { useAppStore } from "./useAppStore";
import { useServerStore } from "./useServerCheck";

type StartupStatus =
	| "loading"
	| "validating"
	| "scannerMode"
	| "normalScanner"
	| "checkingUpdates"
	| "opening"
	| "error";

export function useAppStartup() {
	const [ready, setReady] = useState(false);
	const [status, setStatus] = useState<StartupStatus>("loading");
	const [startupRoute, setStartupRoute] = useState<string | null>(null);

	const hasRunKey = useRef<string | null>(null);

	const hasHydrated = useAppStore((s) => s.hasHydrated);
	const serverPort = useAppStore((s) => s.serverPort);
	const serverIp = useAppStore((s) => s.serverIp);

	setApiConfig({
		serverIp,
		serverPort,
	});

	useEffect(() => {
		if (!hasHydrated) {
			setStatus("loading");
			return;
		}

		const runKey = `${serverIp}:${serverPort}`;

		if (hasRunKey.current === runKey) {
			return;
		}

		hasRunKey.current = runKey;

		let cancelled = false;

		const startup = async () => {
			try {
				setReady(false);
				setStartupRoute(null);

				await devDelay(1500);
				if (cancelled) return;

				setStatus("validating");
				await devDelay(1500);
				if (cancelled) return;

				const hasValidSetup = useAppStore.getState().hasValidSetup;

				if (!hasValidSetup()) {
					setStartupRoute("/setup");
					setReady(true);
					return;
				}

				await versionCheck();

				setStatus("scannerMode");
				await devDelay(1500);
				if (cancelled) return;

				if (parseInt(serverPort || "0", 10) >= 50000) {
					setStatus("normalScanner");
					await devDelay(1500);

					setStartupRoute("/scanner");
					setReady(true);
					return;
				}

				setStatus("checkingUpdates");
				console.log("checking updates");
				await devDelay(1500);
				if (cancelled) return;

				setStatus("opening");
				console.log("opening");
				await devDelay(1500);
				if (cancelled) return;

				setStartupRoute("/(tabs)/scanner");
				console.log("scanner");
				setReady(true);
			} catch (error) {
				console.log("Startup error:", error);
				setStatus("error");
			}
		};

		startup();

		return () => {
			cancelled = true;
		};
	}, [hasHydrated, serverIp, serverPort]);

	return {
		ready,
		startupRoute,
		status,
	};
}
