import React, { useState } from 'react';
import { StyleSheet, ImageBackground, View, TouchableOpacity, Keyboard, Image } from 'react-native';
import { TopNavigation, TopNavigationAction, Input, Text, Icon, IconElement } from '@ui-kitten/components';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { rpx } from '../../utils/rpx';
import { apiService } from '../../utils/api';
import { RootStackParamList } from '../../navigation/types';

interface ErrorState {
    phone: string;
    code: string;
    password: string;
}

type ResetPasswordScreenNavigationProp = StackNavigationProp<RootStackParamList, 'ResetPassword'>;

const BackIcon = (props): IconElement => (
    <Icon
        {...props}
        name='arrow-back'
    />
);

const ResetPasswordScreen = () => {
    const navigation = useNavigation<ResetPasswordScreenNavigationProp>();
    const [phone, setPhone] = useState('');
    const [code, setCode] = useState('');
    const [password, setPassword] = useState('');
    const [uuid, setUuid] = useState('');
    const [loading, setLoading] = useState(false);
    const [countdown, setCountdown] = useState(0);
    const [errors, setErrors] = useState<ErrorState>({
        phone: '',
        code: '',
        password: '',
    });

    const BackAction = (): React.ReactElement => (
        <TopNavigationAction 
            icon={BackIcon} 
            onPress={() => navigation.navigate('Login')}
        />
    );

    const validateForm = () => {
        let isValid = true;
        const newErrors: ErrorState = {
            phone: '',
            code: '',
            password: '',
        };

        // 验证手机号
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phone.trim()) {
            newErrors.phone = '请输入手机号';
            isValid = false;
        } else if (!phoneRegex.test(phone)) {
            newErrors.phone = '请输入正确的手机号格式';
            isValid = false;
        }

        // 验证验证码
        const codeRegex = /^\d{4}$/;
        if (!code.trim()) {
            newErrors.code = '请输入验证码';
            isValid = false;
        } else if (!codeRegex.test(code)) {
            newErrors.code = '请输入4位数字验证码';
            isValid = false;
        }

        // 验证密码
        if (!password.trim()) {
            newErrors.password = '请输入密码';
            isValid = false;
        } else if (password.length < 6) {
            newErrors.password = '密码长度不能少于6位';
            isValid = false;
        }

        setErrors(newErrors);
        return isValid;
    };

    const handleGetCode = async () => {
        const phoneRegex = /^1[3-9]\d{9}$/;
        Keyboard.dismiss();
        
        if (!phone.trim() || !phoneRegex.test(phone)) {
            setErrors({ ...errors, phone: '请输入正确的手机号格式' });
            return;
        }

        try {
            const res = await apiService.getPhoneCode(phone, '3'); // type=3 表示重置密码
            if (res.code === 200) {
                setUuid(res.uuid);
                setCountdown(60);
                const timer = setInterval(() => {
                    setCountdown((prev) => {
                        if (prev <= 1) {
                            clearInterval(timer);
                            return 0;
                        }
                        return prev - 1;
                    });
                }, 1000);
            }
        } catch (error) {
            console.error('获取验证码失败:', error);
        }
    };

    const handleResetPassword = async () => {
        if (!validateForm()) return;
        if (!uuid) {
            return;
        }
        
        setLoading(true);
        try {
            const res = await apiService.resetPassword(phone, password, code, uuid);
            if (res.code === 200) {
                navigation.navigate('Login');
            }
        } catch (error) {
            console.error('重置密码失败:', error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <>
            <ImageBackground
                source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uWOnjtkaVDDLhY4PtMd8' }}
                style={styles.backgroundImage}
            >
                <TopNavigation
                    title='忘记密码'
                    alignment='center'
                    accessoryLeft={BackAction}
                    style={[styles.topNav, { paddingHorizontal: rpx(32) }]}
                />
            </ImageBackground>
            
            <View style={styles.overlay}>
                <Text style={styles.tip}>请输入手机号码和验证码找回密码</Text>
                
                <View style={styles.inputBox}>
                    <Image 
                        source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uAjqjitdgGf19n0G3uuI' }} 
                        style={styles.inputIcon} 
                    />
                    <Input
                        placeholder='请输入手机号'
                        value={phone}
                        onChangeText={value => {
                            setPhone(value);
                            setErrors({ ...errors, phone: '' });
                        }}
                        status={errors.phone ? 'danger' : 'basic'}
                        caption={errors.phone}
                        style={[styles.input, { backgroundColor: 'transparent' }]}
                        textStyle={{ color: '#000' }}
                        keyboardType="phone-pad"
                        maxLength={11}
                    />
                </View>

                <View style={styles.inputBox}>
                    <Image 
                        source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/ud4QtAXZp6fOitzpapuw' }}
                        style={styles.inputIcon} 
                    />
                    <Input
                        placeholder='请输入新密码'
                        value={password}
                        onChangeText={value => {
                            setPassword(value);
                            setErrors({ ...errors, password: '' });
                        }}
                        status={errors.password ? 'danger' : 'basic'}
                        caption={errors.password}
                        style={[styles.input, { backgroundColor: 'transparent' }]}
                        textStyle={{ color: '#000' }}
                        secureTextEntry
                    />
                </View>

                <View style={styles.inputBox}>
                    <Image 
                        source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/u7H7WpZhmsvtgZawoxW6' }}
                        style={styles.inputIcon} 
                    />
                    <Input
                        placeholder='请输入验证码'
                        value={code}
                        onChangeText={value => {
                            setCode(value);
                            setErrors({ ...errors, code: '' });
                        }}
                        status={errors.code ? 'danger' : 'basic'}
                        caption={errors.code}
                        style={[styles.input2, { backgroundColor: 'transparent' }]}
                        textStyle={{ color: '#000' }}
                        keyboardType="number-pad"
                        maxLength={4}
                    />
                    <TouchableOpacity 
                        onPress={handleGetCode}
                        disabled={countdown > 0}
                    >
                        <Text style={[styles.getCode, countdown > 0 && styles.getCodeDisabled]}>
                            {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                        </Text>
                    </TouchableOpacity>
                </View>

                <TouchableOpacity 
                    style={styles.submitButton}
                    onPress={handleResetPassword}
                    disabled={loading}
                >
                    <Text style={styles.submitButtonText}>
                        {loading ? '处理中...' : '确认'}
                    </Text>
                </TouchableOpacity>
            </View>
        </>
    );
};

const styles = StyleSheet.create({
    backgroundImage: {
        width: rpx(750),
        height: rpx(472),
    },
    topNav: {
        backgroundColor: 'transparent',
    },
    overlay: {
        flex: 1,
        marginTop: rpx(-72),
        backgroundColor: '#fff',
        borderTopLeftRadius: rpx(40),
        borderTopRightRadius: rpx(40),
        padding: rpx(68),
    },
    tip: {
        marginBottom: rpx(48),
        fontSize: rpx(28),
        color: '#999',
    },
    inputBox: {
        paddingLeft: rpx(36),
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: rpx(32),
        width: rpx(614),
        height: rpx(108),
        backgroundColor: '#EFEFEF',
        borderRadius: rpx(54),
    },
    inputIcon: {
        width: rpx(38),
        height: rpx(38),
    },
    input: {
        width: rpx(500),
        borderWidth: 0,
    },
    input2: {
        width: rpx(350),
        borderWidth: 0,
    },
    getCode: {
        fontWeight: '400',
        fontSize: rpx(28),
        color: '#4297F3',
        marginRight: rpx(36),
    },
    getCodeDisabled: {
        color: '#999',
    },
    submitButton: {
        marginTop: rpx(68),
        height: rpx(108),
        backgroundColor: '#4297F3',
        borderRadius: rpx(54),
        justifyContent: 'center',
        alignItems: 'center',
    },
    submitButtonText: {
        color: '#fff',
        fontSize: rpx(36),
        fontWeight: 'bold',
    },
});

export default ResetPasswordScreen;