import React, { useState } from 'react';
import { View, TextInput, TouchableOpacity, Text, StyleSheet, ActivityIndicator } from 'react-native';
import { FreechargePersonalBindResult, WalletType } from './types';
import { Locale, defaultLocale } from './locale';

interface Props {
    isDebug: boolean;
    onRequestOTP: (walletType: WalletType, params: any) => Promise<any>;
    onVerifyOTP: (walletType: WalletType, params: any) => Promise<any>;
    processString: string;
    onSuccess: (result: FreechargePersonalBindResult) => void;
    onError: (error: string) => void;
    locale?: Locale;
}

export const FreechargePersonalBind: React.FC<Props> = ({ isDebug, onRequestOTP, onVerifyOTP, processString, onSuccess, onError, locale = defaultLocale }) => {
    const [mobile, setMobile] = useState('');
    const [otp, setOtp] = useState('');
    const [step, setStep] = useState<'mobile' | 'otp' | 'processing' | 'success'>('mobile');
    const [loading, setLoading] = useState(false);
    const [otpData, setOtpData] = useState<any>(null);

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

    const error = (...args: any[]) => {
        if (isDebug) console.error('[Freecharge]', ...args);
    };

    const requestOTP = async () => {
        if (!mobile || mobile.length !== 10) {
            onError(locale.errors.invalidMobile);
            return;
        }

        setLoading(true);
        log('Requesting OTP for:', mobile);

        try {
            const response = await onRequestOTP(WalletType.FREECHARGE_PERSONAL, {
                mobile,
            });
            log('OTP response:', response);

            if (response.success) {
                setOtpData(response.data);
                setStep('otp');
            } else {
                error('OTP request failed:', response.message);
                onError(response.message || locale.errors.otpRequestFailed);
            }
        } catch (e) {
            error('Request OTP error:', e);
            onError(e instanceof Error ? e.message : locale.errors.otpRequestFailed);
        } finally {
            setLoading(false);
        }
    };

    const verifyOTP = async () => {
        if (!otp || otp.length !== 4) {
            onError(locale.freecharge.invalidOtp);
            return;
        }

        setLoading(true);
        setStep('processing');
        log('Verifying OTP:', otp);

        try {
            const response = await onVerifyOTP(WalletType.FREECHARGE_PERSONAL, {
                mobile,
                otp,
                otpId: otpData.otpId,
                deviceId: otpData.deviceId,
                csrfId: otpData.csrfId,
                appFc: otpData.appFc,
            });

            log('Verify response:', response);
            
            if (response.success) {
                onSuccess({
                    type: WalletType.FREECHARGE_PERSONAL,
                    success: true,
                    mobile: response.data.mobile,
                    token: response.data.token,
                    imsId: response.data.imsId,
                    userId: response.data.userId,
                    deviceId: response.data.deviceId,
                    vpas: response.data.vpas,
                    csrfId: response.data.csrfId,
                });
                setStep('success');
            } else {
                error('Verify failed:', response.message);
                setStep('otp');
                onError(response.message || locale.errors.otpVerifyFailed);
            }
        } catch (e) {
            error('Verify OTP error:', e);
            setStep('otp');
            onError(e instanceof Error ? e.message : locale.errors.otpVerifyFailed);
        } finally {
            setLoading(false);
        }
    };

    if (step === 'processing') {
        return (
            <View style={styles.container}>
                <ActivityIndicator size="large" color="#fff" />
                <Text style={styles.processingText}>{processString || locale.common.processing}</Text>
            </View>
        );
    }

    return (
        <View style={styles.container}>
            <View style={styles.form}>
                <Text style={styles.title}>{locale.freecharge.title}</Text>
                
                {step === 'mobile' && (
                    <>
                        <TextInput
                            style={styles.input}
                            placeholder={locale.freecharge.mobilePlaceholder}
                            placeholderTextColor="#999"
                            keyboardType="phone-pad"
                            maxLength={10}
                            value={mobile}
                            onChangeText={setMobile}
                            editable={!loading}
                        />
                        <TouchableOpacity
                            style={[styles.button, loading && styles.buttonDisabled]}
                            onPress={requestOTP}
                            disabled={loading}
                        >
                            {loading ? (
                                <ActivityIndicator color="#fff" />
                            ) : (
                                <Text style={styles.buttonText}>{locale.common.requestOTP}</Text>
                            )}
                        </TouchableOpacity>
                    </>
                )}

                {step === 'otp' && (
                    <>
                        <Text style={styles.hint}>{locale.common.otpSentTo.replace('{mobile}', mobile)}</Text>
                        <TextInput
                            style={styles.input}
                            placeholder={locale.freecharge.otpPlaceholder}
                            placeholderTextColor="#999"
                            keyboardType="number-pad"
                            maxLength={4}
                            value={otp}
                            onChangeText={setOtp}
                            editable={!loading}
                        />
                        <TouchableOpacity
                            style={[styles.button, loading && styles.buttonDisabled]}
                            onPress={verifyOTP}
                            disabled={loading}
                        >
                            {loading ? (
                                <ActivityIndicator color="#fff" />
                            ) : (
                                <Text style={styles.buttonText}>{locale.common.verifyAndBind}</Text>
                            )}
                        </TouchableOpacity>
                        <TouchableOpacity
                            style={styles.linkButton}
                            onPress={() => setStep('mobile')}
                            disabled={loading}
                        >
                            <Text style={styles.linkText}>{locale.common.reEnterMobile}</Text>
                        </TouchableOpacity>
                    </>
                )}
            </View>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.8)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    form: {
        width: '80%',
        backgroundColor: '#fff',
        borderRadius: 10,
        padding: 20,
    },
    title: {
        fontSize: 20,
        fontWeight: 'bold',
        textAlign: 'center',
        marginBottom: 20,
    },
    input: {
        borderWidth: 1,
        borderColor: '#ddd',
        borderRadius: 5,
        padding: 12,
        fontSize: 16,
        marginBottom: 15,
    },
    button: {
        backgroundColor: '#007AFF',
        borderRadius: 5,
        padding: 15,
        alignItems: 'center',
    },
    buttonDisabled: {
        backgroundColor: '#ccc',
    },
    buttonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    linkButton: {
        marginTop: 10,
        alignItems: 'center',
    },
    linkText: {
        color: '#007AFF',
        fontSize: 14,
    },
    hint: {
        fontSize: 14,
        color: '#666',
        marginBottom: 10,
        textAlign: 'center',
    },
    processingText: {
        color: '#fff',
        fontSize: 16,
        marginTop: 10,
    },
});