import { useUserAuthenticationContext } from "@/contexts/UserAuthenticationContext";
import type { MainStackScreenComponentProps } 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 InputWithTopLabel from "@components/InputWithTopLabel";
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 { TouchableOpacity, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

import { LOG } from "@logger";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";

const log = LOG.extend("UserLoginScreen");
const UserLoginScreen: MainStackScreenComponentProps<"userLoginScreen"> = ({ navigation }) => {
	log.debug("UserLoginScreen");
	const insets = useSafeAreaInsets();
	const { setAuthenticationData, setUserInformations } = useUserAuthenticationContext();

	// TODO : Remove default value for email and password
	const [email, setEmail] = useState("admin");
	const [password, setPassword] = useState("admin");
	const [error, setError] = useState("");

	const authenticationMutation = useMutation({
		mutationFn: authenticateUser,
		onSuccess: (data) => {
			setAuthenticationData(data);
			// navigation.popToTop();
			// navigation.replace("bottomTabs");
			// navigation.navigate("bottomTabs");
			log.info("Receive data from authenticateUser, running getUserInformations...");
			userInformationsMutation.mutate(data.access);
			// console.log("user informations", userInformations);
		},
		// biome-ignore lint/suspicious/noExplicitAny: <Axios error>
		onError: (error: AxiosError<any>) => {
			log.error("authenticationMutation", error);
			if (error.response) {
				log.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: (userInformations) => {
			log.info("getUserInformations request was a success, navigating to homepage");
			setUserInformations(userInformations);
			navigation.navigate("appBottomTabsNavigator");
		},
		onError: (error) => {
			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 }]}>
				<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>
					<KeyboardAwareScrollView
						onKeyboardDidShow={() => {
							log.debug("Keyboard did show");
						}}
					>
						<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"}>
								<InputWithTopLabel
									label="Email"
									// value={email}
									autoCorrect={false}
									textContentType="emailAddress"
									onChangeText={(email) => setEmail(email)}
								/>
								<InputWithTopLabel
									label="Mot de passe"
									secureTextEntry={true}
									textContentType="oneTimeCode"
									// value={password}
									onChangeText={(text) => setPassword(text)}
								/>
							</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>
					</KeyboardAwareScrollView>
				</ContainerBorderTopCurved>
			</View>
		</BackgroundDefault>
	);
};

export default UserLoginScreen;
