import axios from "axios";

import { useRouter } from "expo-router";
import { Settings } from "lucide-react-native";
import { useState } from "react";
import { Alert, Button, Text, View } from "react-native";
import Toast from "react-native-toast-message";
import { ConfigButton } from "../components/ui/configButton";
import { Input } from "../components/ui/input";
import { useAppStore } from "../hooks/useAppStore";
import { useMobileAuthStore } from "../hooks/useMobileAuth";

const formatName = (name?: string) =>
	name ? name.charAt(0).toUpperCase() + name.slice(1).toLowerCase() : "";

export default function Login() {
	// doing this causes rerender and sub
	//const { setUser } = useMobileAuthStore();
	const [pin, setPin] = useState("");
	const serverPort = useAppStore((s) => s.serverPort);
	const serverIp = useAppStore((s) => s.serverIp);

	const router = useRouter();

	const onLogin = async () => {
		if (pin.length < 6) {
			console.log("pin must be min 6 ");
		}
		console.log(pin);
		try {
			const res = await axios.post(
				`http://${serverIp}:${parseInt(serverPort || "0", 10) >= 50000 ? "3000" : serverPort}/lst/api/mobile/auth/pin`,
				{ pin },

				{
					timeout: 5000,
				},
			);

			if (res.status === 200) {
				// this way to set the user is direct and basically a 1 shot
				Toast.show({
					type: "success",
					text1: `Welcome back ${formatName(res.data.data.name)}`,
				});
				useMobileAuthStore.getState().setUser(res.data.data);
				return router.replace("/(tabs)/scanner");
			}
		} catch (error) {
			console.log(error);
			//Alert.alert("Login Error", `Invalid pin please try again`);

			Toast.show({ type: "error", text1: `Invalid pin please try again` });
		}
	};

	return (
		<View
			style={{
				flex: 1,
				//justifyContent: "center",
				alignItems: "center",
				marginTop: 50,
			}}
		>
			<View className="flex items-center m-5">
				<View className="flex flex-row">
					<View>
						<Text style={{ fontSize: 20, fontWeight: "600" }} className="mt-2">
							LST Scanner Login
						</Text>
					</View>
					<View>
						<ConfigButton />
					</View>
				</View>

				<View className="w-64 p-4">
					<Input
						className="w-fit"
						keyboardType="number-pad"
						textContentType="oneTimeCode"
						placeholder="Pin number"
						onChangeText={setPin}
					/>
				</View>
			</View>
			<View>
				<Text className="p-3">
					Warning: If you are logged into another scanner you will encounter
					scan errors, please do not try to log into more than 1 scanner at a
					time.
				</Text>
			</View>
			<View className="flex gap-2 flex-row">
				<Button title="Login" onPress={onLogin} />
			</View>
		</View>
	);
}
