import {
	type IorangePaymentStarter,
	getTransactionStatus,
	getTransactionsData,
} from "@/utils/requests/orangePayment";
import { LOG } from "@logger";

import { useMutation } from "@tanstack/react-query";
import * as WebBrowser from "expo-web-browser";
import { useState } from "react";

const log = LOG.extend("useOrangeMoney");

const paymentObjectDefault: IorangePaymentStarter = {
	// biome-ignore lint/style/useNamingConvention: <api expect type_paiement>
	type_paiement: 1,
	marchand: "1",
	service: "1",
	montant: 0,
	numero: "0707070707",
	commentaire: "Un commentaire",
};
const useOrangeMoney = () => {
	const [isBrowserOpen, setIsBrowserOpen] = useState(false);

	const handlePaymentUsingBrowser = async (url: string) => {
		setIsBrowserOpen(true);
		const result = await WebBrowser.openBrowserAsync(url);
		// setResult(result);
		log.debug("Result after browser closed :: ", result);
		setIsBrowserOpen(false);
	};

	const orangeTransactionInitializerMutation = useMutation({
		mutationFn: (amount: number) =>
			getTransactionsData({
				...paymentObjectDefault,
				montant: amount,
			}),
		onSuccess: async (data) => {
			// return data.payment_url
			log.debug("orangeTransactionInitializerMutation request success, opening browser...");
			await handlePaymentUsingBrowser(data.payment_url);
			// await transactionsStatusMutation.mutate(data.order_id);
			// setResult(result);
		},
		onError: (err) => {
			log.error("orangeTransactionInitializerMutation |", err);
		},
	});

	const maxRetry = 3;
	const retryDelay = 5000;

	const transactionsStatusMutation = useMutation({
		mutationFn: (orderId: string) => getTransactionStatus(orderId),
		onSuccess: (data) => {
			log.debug("transactionsStatusMutation request success");
			return data.status;
		},
		onError: (err) => {
			log.error("transactionsStatusMutation |", err);
		},
		retry: (failureCount, error) => {
			log.warn("transactionsStatusMutation | retrying", failureCount, error);
			return failureCount < maxRetry;
		},
		retryDelay(_failureCount, _error) {
			return retryDelay;
		},
	});

	return {
		orangeTransactionInitializerMutation: orangeTransactionInitializerMutation,

		handlePaymentUsingBrowser,
		isBrowserOpen,
		isWaitingForOmPaymentUrl: orangeTransactionInitializerMutation.isPending,
		isCheckingForTransactionStatus: transactionsStatusMutation.isPending,
		transactionsStatusMutation,
	};
};

export default useOrangeMoney;
