import React, {useState} from 'react';
import {StyleSheet, Text, TouchableOpacity} from 'react-native';
import type {PaymentConfig} from '@netappsng/react-native-pay';
import {presentPayment} from '@netappsng/react-native-pay';
import {Amount} from "../atoms/Amount";
import {useGameContext} from "../../context/GameContext";
import {wallet} from "../../api/wallet";
import PreLoaderModal from '../atoms/PreLoaderModal';

type Props = {
    amount: number;
};

export function CheckoutScreen({amount}: Props) {

    const {config, setBalance} = useGameContext();
    const [isLoading, setIsLoading] = useState(false);

    const loadBalance = async () => {
        setIsLoading(true)
        try {
            const balance = await wallet(config.userId, amount,'top-up');

            if (balance !== undefined) {
                if (typeof balance === "number") {
                    setBalance(balance);
                }
            }
        } catch (error) {
            console.log(error);
        } finally {
            setIsLoading(false)
        }
    };

    function handlePayment() {
        const amountNaira = amount;
        const amountKobo = Math.round(amountNaira * 100);

        const configure: PaymentConfig = {
            publicKey: 'sk_test_ec2062606b84ef7aaf2fca4f62247a27348cca1656740988',
            // publicKey: 'pk_live_880c15c51cbc19e38c44f44a54fd628d801b05b2ef8d35e4',
            amount: amountKobo,
            currency: 'NGN',
            email: config.email,
            fullName: config.name,
            phoneNumber: config.phoneNumber,
            narration: 'Game wallet top-up',
            paymentChannels: ['card', 'transfer', 'ussd', 'payattitude', 'moniflow'],
            defaultChannel: 'card',
            address1: 'Customer Address',
            metadata: {inputAmount: amountNaira, env: 'development'},
            businessName: 'Floating Games',
            showTransactionSummary: true,
        };

        return presentPayment(configure, {
            onSuccess: (payload:any) => {
                loadBalance()
                console.log('Payment successful!', payload.transactionRef);
            },
            onFailed: (payload:any) => {
                console.log('Payment failed:', payload.message);
            },
            onCancel: () => {
                console.log('Payment cancelled');
            },
            onReady: () => {
                console.log('Payment UI ready');
            },
        });
    }

    return (
        <>
            <PreLoaderModal visible={isLoading} message="Fetching player data..." />

            <TouchableOpacity
                style={[styles.button, styles.button2, {flexDirection: 'row'}]}
                onPress={handlePayment}
            >
                <Text style={[styles.buttonText, {marginEnd: 4}]}>Pay</Text>
                <Amount
                    value={Number(amount)}
                    fontSize={15}
                    color="#fff"
                    fontWeight="normal"
                />
            </TouchableOpacity>
        </>

    );
}

const styles = StyleSheet.create({
    button: {
        padding: 16,
        borderRadius: 10,
        alignItems: 'center',
        justifyContent: 'center',
    },
    buttonText: {
        color: '#eee',
        fontSize: 15,
    },
    button2: {
        backgroundColor: '#22c55e',
    }
})