import { useUserAuthenticationContext } from "@/contexts/UserAuthenticationContext";
import type { UnloggedUserStackScreenComponentProps } from "@/navigations/Types";
import authenticateUser from "@/utils/requests/authenticateUser";
import getUserInformations from "@/utils/requests/userInformations";
import Button from "@components/Button";
import ContainerBorderTopCurved from "@components/ContainerBorderTopCurved";
import Input from "@components/Input";
import BackgroundDefault from "@components/backgrounds/BackgroundDefault";
import Box from "@components/bases/Box";
import Text from "@components/bases/Text";
import { Fontisto } from "@expo/vector-icons";
import { containers } from "@styles/Commons";
import { useMutation } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import { useCallback, useState } from "react";
import { KeyboardAvoidingView, Platform, TouchableOpacity, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

const UserLoginScreen: UnloggedUserStackScreenComponentProps<"userLoginScreen"> = ({
	navigation,
}) => {
	const insets = useSafeAreaInsets();
	const { setAuthenticationData } = useUserAuthenticationContext();

	const [email, setEmail] = useState("");
	const [password, setPassword] = useState("");
	const [error, setError] = useState("");

	const authenticationMutation = useMutation({
		mutationFn: authenticateUser,
		onSuccess: (data) => {
			setAuthenticationData(data);
			// navigation.popToTop();
			// navigation.replace("bottomTabs");
			// navigation.navigate("bottomTabs");
			const userInformations = userInformationsMutation.mutate(data.access);
			console.log(userInformations);
		},
		// biome-ignore lint/suspicious/noExplicitAny: <Axios error>
		onError: (error: AxiosError<any>) => {
			if (error.response) {
				console.error("error :: ", error.response.data);
				if (error.response.status === 400) {
					return setError("Bad request");
				}
				const message: string = error.response.data.detail;
				return setError(message);
			}
			setError("Unknown error");
		},
	});

	const userInformationsMutation = useMutation({
		mutationFn: (userAccessToken: string) => getUserInformations(userAccessToken),
		onSuccess: (data) => {
			console.log("Data userInformationsMutation", data);

			// TODO : Navigate to bottomTabs
			navigation.navigate("bottomTabs");
		},
		onError: (error) => {
			console.log("Error userInformationsMutation", error);
		},
	});

	const submit = useCallback(() => {
		authenticationMutation.mutate({
			username: email,
			password: password,
		});
	}, [email, password, authenticationMutation]);

	return (
		<BackgroundDefault>
			<View style={[containers.containerFull, { paddingTop: insets.top }]}>
				<KeyboardAvoidingView
					behavior={Platform.OS === "ios" ? "padding" : "position"}
					style={{ flex: 1 }}
				>
					<Box style={{ height: "20%" }} px={"l"}>
						<Box
							px={"m"}
							justifyContent={"space-between"}
							flexDirection={"row"}
							alignItems={"center"}
						>
							<TouchableOpacity onPress={() => navigation.goBack()}>
								<Fontisto name="close-a" size={12} color="black" />
							</TouchableOpacity>

							<TouchableOpacity>
								<Text>Mot de passe oublie ?</Text>
							</TouchableOpacity>
						</Box>
					</Box>
					<ContainerBorderTopCurved>
						<Box p={"l"} paddingTop={"x100"} mb={"s"}>
							<Box mb={"l"}>
								<Text fontSize={40} fontWeight={"bold"} variant={"black"}>
									Connexion
								</Text>
								<Text color={"gray"}>Bienvenue, vous nous avez manqué !</Text>
							</Box>

							<Box gap={"m"}>
								<Input
									label="Email"
									// value={email}
									autoCorrect={false}
									textContentType="emailAddress"
									onChangeText={setEmail}
								/>
								<Input
									label="Mot de passe"
									secureTextEntry={true}
									textContentType="oneTimeCode"
									// value={password}
									onChangeText={setPassword}
								/>
							</Box>
						</Box>
						{error && (
							<Text variant={"error"} textAlign={"center"}>
								{error}
							</Text>
						)}
						<Box p={"s"}>
							<Button
								variant={"full"}
								textVariants={"primary"}
								label="Se connecter"
								onPress={() => {
									// navigation.popToTop();
									// navigation.navigate("bottomTabs");
									submit();
								}}
							/>
							<Button
								variant={"lightGray"}
								textVariants={"black"}
								label="Creer un compte"
								onPress={() => {}}
							/>
						</Box>
					</ContainerBorderTopCurved>
				</KeyboardAvoidingView>
			</View>
		</BackgroundDefault>
	);
};

export default UserLoginScreen;
