import type { PaymentStackScreenComponentProps } from "@/navigations/Types";
import BeasyLogoIcon from "@components/BeasyLogoIcon";
import Button from "@components/Button";
import GoBackIconButton from "@components/GoBackIconButton";
import Input from "@components/Input";
import PaymentOption from "@components/PaymentOption";
import BackgroundDefault from "@components/backgrounds/BackgroundDefault";
import Box from "@components/bases/Box";
import Text from "@components/bases/Text";
import useOrangeMoney from "@hooks/useOrangeMoney";
import { LOG } from "@logger";
import { useCallback, useState } from "react";
import { Keyboard, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

const log = LOG.extend("PaymentAmountInputScreen");
const PaymentAmountInputScreen: PaymentStackScreenComponentProps<"paymentAmountInputScreen"> = ({
	route,
	navigation,
}) => {
	log.debug("PaymentAmountInputScreen");
	const { paymentType } = route.params;
	const [amountToPay, setAmountToPay] = useState(0);

	const {
		orangeTransactionInitializerMutation,
		handlePaymentUsingBrowser,
		isBrowserOpen,
		isWaitingForOmPaymentUrl,
		isCheckingForTransactionStatus,
		transactionsStatusMutation,
	} = useOrangeMoney();

	const insets = useSafeAreaInsets();

	log.debug({
		isWaitingForOmPaymentUrl,
		isCheckingForTransactionStatus,
		isBrowserOpen,
	});

	const updateAmountToPay = (amount: string) => {
		const amountParsed = Number.parseInt(amount);
		if (!Number.isNaN(amountParsed)) {
			return setAmountToPay(amountParsed);
		}

		return setAmountToPay(0);
	};

	const handlePaymentButton = useCallback(async () => {
		switch (paymentType) {
			case "OM": {
				Keyboard.dismiss();
				log.info("OM so we stays on screen !!");
				log.info("Calling api with amount :: ", amountToPay);

				const { payment_url, order_id } =
					await orangeTransactionInitializerMutation.mutateAsync(amountToPay);
				log.info("Url de paiement orange", payment_url);
				log.info("Ouverture du navigateur sur la page de paiement...");
				await handlePaymentUsingBrowser(payment_url);
				log.info("Verifying transaction status...");
				const response = await transactionsStatusMutation.mutateAsync(order_id);
				log.info("result of transactions", JSON.stringify(response, null, 2));
				// log.info(
				// 	`Was the transaction initialization a success ? ${orangeTransactionInitializerMutation.isSuccess}`,
				// );
				// if (orangeTransactionInitializerMutation.isSuccess) {
				// 	log.info("initilization was a success, checking for status");
				// 	await transactionsStatusMutation.mutateAsync(
				// 		orangeTransactionInitializerMutation.data.order_id,
				// 	);
				// 	log.info(
				// 		"result of transactions",
				// 		JSON.stringify(transactionsStatusMutation.data, null, 2),
				// 	);
				// }

				// console.log("Response transaction", response);
				break;
			}
			default:
				log.info("Navigating to numberAndOtpForPaymentScreen");
				navigation.navigate("numberAndOtpForPaymentScreen");
				break;
		}
	}, [
		amountToPay,
		orangeTransactionInitializerMutation,
		paymentType,
		navigation,
		transactionsStatusMutation,
		handlePaymentUsingBrowser,
	]);

	return (
		<BackgroundDefault>
			{/* <SafeAreaView> */}

			{transactionsStatusMutation.isPending && <LoadingScreen />}
			<Box
				style={{
					height: "100%",
					width: "100%",
					marginTop: insets.top,
				}}
			>
				<Box
					px={"l"}
					flexDirection={"row"}
					justifyContent={"space-between"}
					alignItems={"center"}
					mb={"m"}
				>
					<BeasyLogoIcon />
					<GoBackIconButton onPress={() => navigation.goBack()} />
				</Box>
				{/* <Box height={150} alignItems={"center"} justifyContent={"center"}>
						<BalanceContainer balance={78000} label="Total des ventes" />
					</Box> */}
				<Box height={90} padding={"s"} paddingLeft={"l"}>
					<Text color={"black"}>Montant à payé</Text>
					<Text color={"black"} variant={"header"}>
						{amountToPay}
					</Text>
				</Box>
				<Box
					p={"l"}
					paddingTop={"xl"}
					backgroundColor={"white"}
					flex={1}
					borderTopLeftRadius={20}
					borderTopRightRadius={20}
				>
					<Box width={75} height={50} mb={"l"} borderRadius={10} overflow={"hidden"}>
						<PaymentOption onPress={() => {}} paymentMethod={paymentType} />
					</Box>
					<Box mb={"xl"}>
						<Input
							label="Entrez le montant"
							autoFocus={true}
							keyboardType="numeric"
							onChangeText={(e) => updateAmountToPay(e)}
						/>
					</Box>
					<Button
						onPress={handlePaymentButton}
						variant={"full"}
						textVariants={"primary"}
						label={`${isWaitingForOmPaymentUrl ? "Chargement..." : "Payer"} `}
					/>
				</Box>
			</Box>
			{/* </SafeAreaView> */}
		</BackgroundDefault>
	);
};

export default PaymentAmountInputScreen;

const LoadingScreen = () => {
	return (
		<View
			style={{
				flex: 1,
				width: "100%",
				height: "100%",
				justifyContent: "center",
				alignItems: "center",
				zIndex: 1000000000000,
				backgroundColor: "black",
				opacity: 0.5,
				position: "absolute",
			}}
		>
			<Text color={"primary"}>Verification du status de la transaction.</Text>
			<Text>Veuillez patienter</Text>
		</View>
	);
};
