import { asp as g } from "@asp/asp";
import { BarnoinPayBackground } from "@components/BarnoinPayBackground";
import BeasyLogoIcon from "@components/BeasyLogoIcon";
import * as Button from "@components/ButtonNew";
import * as Input from "@components/InputNew";
import * as Modal from "@components/Modal";
import { LOG } from "@logger";
import { useMutation } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import * as WebBrowser from "expo-web-browser";
import { useEffect, useRef, useState } from "react";
import { AppState, Text, View } from "react-native";
import {
	omInitializeTransaction,
	omVerifyTransactionStateWithTimeout,
	waveInitializeTransaction,
} from "@/features/pay/api";
import PaymentType from "@/features/pay/components/PaymentType";
import type { PaymentStackScreenComponentProps } from "@/navigations/types";

const log = LOG.extend("PaymentAmountInputScreen");
const PaymentAmountInputScreen: PaymentStackScreenComponentProps<"paymentAmountInputScreen"> = ({
	route,
	navigation,
}) => {
	log.debug("PaymentAmountInputScreen");

	const [amount, setAmount] = useState(0);
	const [error, setError] = useState("");
	const appState = useRef(AppState.currentState);

	const handlePayment = async () => {
		try {
			const code = route.params.paymentType.code;
			if (code === "OM") {
				// TODO: ASK THE BOSS WHY THE PAYLOAD IS MOSTLY USELESS HERE.
				const res = await omInitializeTransaction({
					type_paiement: 1,
					marchand: "1",
					service: "1",
					montant: amount,
					commentaire: "un commentaire",
					numero: "0707070707",
				});
				WebBrowser.openBrowserAsync(res.data.payment_url);
			} else if (code === "WAVE") {
				const res = await waveInitializeTransaction({
					type_paiement: 2,
					marchand: "1",
					service: "1",
					montant: amount,
				});
				navigation?.getParent()?.navigate("waveQrCodePaymentScreen", {
					data: res,
				});
			} else {
				navigation.navigate("numberAndOtpForPaymentScreen", {
					paymentType: route.params.paymentType,
					amount: amount,
				});
			}
		} catch (error) {
			const err = error as AxiosError;
			setError(JSON.stringify(err.response?.data) || err.message);
		}
	};

	const omTransactionVerification = useMutation({
		mutationFn: () => omVerifyTransactionStateWithTimeout("1", 10000, 2000),
		onSuccess: (_data) => {
			navigation?.getParent()?.navigate("paymentResultScreen");
		},
		onError: (err: AxiosError) => {
			setError(JSON.stringify(err.response?.data) || err.message);
		},
	});

	useEffect(() => {
		if (route.params.paymentType.code !== "OM") return; // only for orange money payment should this effect be run
		const subscription = AppState.addEventListener("change", (nextAppState) => {
			if (
				appState.current.match(/inactive|background/) &&
				nextAppState === "active" &&
				route.params.paymentType.code === "OM"
			) {
				console.log("App has come to the foreground!");
				omTransactionVerification.mutate();
			}

			appState.current = nextAppState;

			console.log("AppState", appState.current);
		});

		return () => {
			subscription.remove();
		};
	}, [route, omTransactionVerification]);

	// 	switch (paymentType) {
	// 		case "OM": {
	// 			Keyboard.dismiss();
	// 			log.info("OM so we stays on screen !!");
	// 			// await orangePaymentSequence();
	// 			try {
	// 				await orangePaymentTransactionHandler(amountToPay);
	// 				// navigation.getParent()?.navigate("paymentResultScreen");
	// 			} catch (error) {
	// 				log.error("handlePaymentButton |", error);
	// 			}

	// 			break;
	// 		}
	// 		case "WAVE": {
	// 			try {
	// 				log.info("Wave so we stay on screen.");
	// 				await waveTransactionHandler(amountToPay);
	// 			} catch (error) {
	// 				log.error("handlePaymentButton Wave|", error);
	// 			}
	// 			break;
	// 		}
	// 		default:
	// 			log.info("Navigating to numberAndOtpForPaymentScreen");
	// 			navigation.navigate("numberAndOtpForPaymentScreen");
	// 			break;
	// 	}
	// }, [
	// 	paymentType,
	// 	navigation,
	// 	amountToPay,
	// 	orangePaymentTransactionHandler,
	// 	waveTransactionHandler,
	// ]);

	return (
		<BarnoinPayBackground style={[g.flex_col, g.gap_lg, g.relative]}>
			<View style={[g.px_lg]}>
				<BeasyLogoIcon />
			</View>

			<View style={[g.px_lg]}>
				<Text style={[g.font_bold, g.text_2xl]}>Montant à payé </Text>
				<Text style={[g.font_bold, g.text_2xl]}>{amount}</Text>
			</View>

			<View
				style={[
					g.flex_1,
					g.p_5xl,
					g.gap_5xl,
					{ backgroundColor: "white", borderTopLeftRadius: 20, borderTopRightRadius: 20 },
				]}
			>
				<PaymentType type={route.params.paymentType.code} />
				<Input.Container>
					<Input.Header>Entrer le montant</Input.Header>
					<Input.FieldContainer>
						<Input.Field
							keyboardType="number-pad"
							value={amount === 0 ? "" : amount.toString()}
							onChangeText={(v) => setAmount(Number(v))}
						/>
					</Input.FieldContainer>
				</Input.Container>

				<Button.Container onPress={handlePayment}>
					<Button.Label>Payer</Button.Label>
				</Button.Container>
			</View>

			<Modal.RnModal visible={!!error} style={{ backgroundColor: "rgba(0, 0, 0, 0.25)" }}>
				<Modal.OuterView style={[g.p_md, g.shadow_elevated, { backgroundColor: "white" }]}>
					<Text>{error}</Text>

					<Button.Container onPress={() => setError("")}>
						<Button.Label>OK</Button.Label>
					</Button.Container>
				</Modal.OuterView>
			</Modal.RnModal>

			<Modal.RnModal
				visible={omTransactionVerification.isPending}
				style={{ backgroundColor: "rgba(0, 0, 0, 0.25)" }}
			>
				<Modal.OuterView style={[g.p_md, g.shadow_elevated, { backgroundColor: "white" }]}>
					<Text>Loading...</Text>
				</Modal.OuterView>
			</Modal.RnModal>
		</BarnoinPayBackground>
	);
};

export default PaymentAmountInputScreen;
