import React, { useEffect, useState } from 'react';
import { View, StyleSheet, Text, NativeModules } from 'react-native';
import { PaytmPersonalBindResult, ProfileDetail, WalletType } from './types';
import { Locale, defaultLocale } from './locale';

const { PaytmPersonalModule } = NativeModules;

interface Props {
    isDebug: boolean;
    processString: string;
    onSuccess: (result: PaytmPersonalBindResult) => void;
    onError: (error: string) => void;
    locale?: Locale;
}

export const PaytmPersonalBind: React.FC<Props> = ({ isDebug, processString, onSuccess, onError, locale = defaultLocale }) => {
    const [status, setStatus] = useState<'idle' | 'requesting'>('idle');

    const log = (...args: any[]) => {
        if (!isDebug) return;
        console.log('[PaytmPersonal]', ...args);
    };

    useEffect(() => {
        requestToken();
    }, []);

    const requestToken = async () => {
        if (!PaytmPersonalModule) {
            onError(locale.errors.nativeModuleNotAvailable);
            return;
        }

        try {
            setStatus('requesting');
            log('Requesting token from Paytm...');
            
            const result = await PaytmPersonalModule.getToken();
            const data = JSON.parse(result);
            
            log('Token received:', data);
            
            // 获取 UPI
            const profileDetail = await fetchUPI(data.token) as ProfileDetail;
            log('Profile detail received:', profileDetail);
            
            onSuccess({
                type: WalletType.PAYTM_PERSONAL,
                success: true,
                mobile: data.mobile,
                token: data.token,
                userId: data.userId,
                profileDetail: profileDetail,
            });
        } catch (e) {
            log('Error:', e);
            onError(e instanceof Error ? e.message : String(e));
        }
    };

    const fetchUPI = async (token: string): Promise<ProfileDetail | undefined> => {
        try {
            const deviceId = Math.random().toString(16).substring(2, 18);
            const timestamp = Date.now();
            
            const url = `https://storefront.paytm.com/v2/h/paytm-homepage?playStore=true&cCode=91&lang_id=1&language=en&locale=en-IN&deviceName=M2004J7AC&version=10.69.0&resolution=4&deviceIdentifier=Xiaomi-M2004J7AC-${deviceId}&osVersion=12&client=androidapp&tag=refresh&deviceManufacturer=Xiaomi&networkType=WIFI&device=android&child_site_id=1&site_id=1`;
            
            const body = {
                context: {
                    user: {
                        ga_id: deviceId,
                        experiment_id: '',
                    },
                    version: '10.69.0',
                    geo: {
                        lat: '',
                        long: '',
                    },
                    device: {
                        ua: 'Mozilla/5.0 (Linux; Android 12) AppleWebKit/537.36',
                        // ip: '11.6.136.115',
                        ip_v6: '',
                        make: 'Xiaomi',
                        model: 'M2004J7AC',
                        osv: '12',
                        connection_type: 'WIFI',
                        carrier: '',
                        aaid: deviceId,
                        device_type: 'PHONE',
                        os: 'Android',
                    },
                    channel: 'APP',
                },
                tracking: {
                    current_page: 'paytm-home',
                    referer_ui_element: '',
                },
            };
            
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'sso_token': token,
                    'x-id': deviceId,
                    'x-app-rid': `${deviceId}:${timestamp}:f:c7`,
                    'x-mfg': 'Xiaomi',
                    'x-nw': 'WIFI',
                    'x-store': '0',
                    'x-vpn': 'true',
                    'x-tamp': '0',
                    'x-intg': '1',
                    'User-Agent': 'Paytm Release/10.69.0/721817 (net.one97.paytm; source=com.android.vending; integrity=true; auth=true; en-IN; okhttp 4.12.0) Android/12 Xiaomi/M2004J7AC',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(body),
            });
            
            const json = await response.json();
            // console.log('Fetch UPI response:', json);
            return json?.metadata?.profile_detail || undefined;
        } catch (e) {
            log('Fetch UPI error:', e);
            return undefined;
        }
    };

    return (
        <View style={styles.container}>
            <View style={styles.overlay}>
                <Text style={styles.overlayText}>
                    {status === 'requesting' ? (processString || locale.paytmPersonal.processing) : locale.common.processing}
                </Text>
            </View>
        </View>
    );
};

export const paytmPay = async (
    amount: string,
    payeeName: string,
    accountNo: string,
    ifscCode: string,
    comments: string
): Promise<boolean> => {
    if (!PaytmPersonalModule) {
        throw new Error('Native module not available');
    }
    return await PaytmPersonalModule.pay(amount, payeeName, accountNo, ifscCode, comments);
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.5)',
    },
    overlay: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    overlayText: {
        color: 'white',
        fontSize: 16,
    },
});
