import React, { useState, useEffect } from 'react';
import { StyleSheet, ImageBackground, View, Image, TouchableOpacity, Keyboard } from 'react-native';
import { Button, Input, Layout, Text, Modal, Card } from '@ui-kitten/components';
import { rpx } from '../../utils/rpx';
import { useNavigation } from '@react-navigation/native';
import { apiService } from '../../utils/api';
import { useAuth } from '../../context/AuthContext';

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

const LoginScreen = () => {
    const navigation = useNavigation();
    const { login } = useAuth(); // 修改这里，使用 login
    const [phone, setPhone] = useState('');
    const [code, setCode] = useState('');
    const [password, setPassword] = useState('');
    const [uuid, setUuid] = useState('');
    const [loading, setLoading] = useState(false);
    const [isCodeLogin, setIsCodeLogin] = useState(true);
    const [isRegister, setIsRegister] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [modalConfig, setModalConfig] = useState({ title: '', message: '' });
    const [countdown, setCountdown] = useState(0);
    const [errors, setErrors] = useState<ErrorState>({
        phone: '',
        code: '',
        password: '',
    });

    useEffect(() => {
        let timer: NodeJS.Timeout;
        if (countdown > 0) {
            timer = setInterval(() => {
                setCountdown(prev => prev - 1);
            }, 1000);
        }
        return () => timer && clearInterval(timer);
    }, [countdown]);

    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;
        }

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

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

        setErrors(newErrors);
        return isValid;
    };

    const handleLogin = async () => {
        Keyboard.dismiss();
        if (!validateForm()) return;

        if ((isCodeLogin || isRegister) && !uuid) {
            return;
        }

        setLoading(true);
        try {
            let res;
            
            if (isRegister) {
                res = await apiService.register(phone, password, code, uuid);
            } else if (isCodeLogin) {
                res = await apiService.phoneCodeLogin(phone, code, uuid);
            } else {
                res = await apiService.passwordLogin(phone, password);
            }
            console.log(res,'res');
            if (res.code === 200) {
                console.log('登录成功，获取到token:', res.token);
                await login(res.token); // 使用 AuthContext 的 login 方法
                // 不需要手动导航，AuthContext 会处理导航
            } else {
                throw new Error(res.msg || '登录失败');
            }
        } catch (error: any) {
            console.error('登录失败:', error);
            setModalConfig({
                title: '登录失败',
                message: error.message || '请稍后重试'
            });
            setModalVisible(true);
        } finally {
            setLoading(false);
        }
    };

    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, isRegister ? '2' : '1');
            if (res.code === 200) {
                setUuid(res.uuid);
                setCountdown(60);
            }
        } catch (error: any) {
            console.error('获取验证码失败:', error);
            setModalConfig({
                title: '获取验证码失败',
                message: error.message || '请稍后重试'
            });
            setModalVisible(true);
        }
    };

    const renderLoginForm = () => (
        <View>
            <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>
            
            {(!isCodeLogin || isRegister) && (
                <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.input2, { backgroundColor: 'transparent' }]}
                        textStyle={{ color: '#000' }}
                        secureTextEntry={true}
                        maxLength={20}
                    />
                    {!isRegister && !isCodeLogin && (
                        <TouchableOpacity 
                            onPress={() => navigation.navigate('ResetPassword' as never)}
                            style={{position: 'absolute', right: rpx(30)}}
                        >
                            <Text style={styles.getCode}>忘记密码？</Text>
                        </TouchableOpacity>
                    )}
                </View>
            )}
            
            {(isCodeLogin || isRegister) && (
                <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 
                onPress={handleLogin} 
                style={styles.loginBtn}
                disabled={loading}
            >
                <Text style={styles.loginTxt}>
                    {loading ? '处理中...' : (isRegister ? '立即注册' : '立即登录')}
                </Text>
            </TouchableOpacity>

            <TouchableOpacity 
                onPress={() => {
                    setIsRegister(!isRegister);
                    setIsCodeLogin(true);
                    setCode('');
                    setPassword('');
                    setErrors({
                        phone: '',
                        code: '',
                        password: '',
                    });
                }} 
                style={{flexDirection:'row',alignItems:'center',justifyContent:'center',marginTop:rpx(68)}}
            >
                <Text style={styles.tipTxt}>{isRegister ? '已有账号？' : '没有账号？'}</Text>
                <Text style={[styles.tipTxt,{color:'#4297F3'}]}>{isRegister ? '去登录' : '去注册'}</Text>
            </TouchableOpacity>
        </View>
    );

    return (
        <>
            <ImageBackground
                source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uWOnjtkaVDDLhY4PtMd8' }}
                style={styles.backgroundImage}
            >
                <View style={styles.overlay}>
                    <Layout style={styles.container} level='1'>
                        {!isRegister && (
                            <View style={styles.tabBarBox}>
                                <TouchableOpacity onPress={() => setIsCodeLogin(true)}>
                                    <Image
                                        source={{ uri: isCodeLogin ? 
                                            'https://lxnapi.ccttiot.com/bike/img/static/uLTEz0tXCElq04X9ruhR' : 
                                            'https://lxnapi.ccttiot.com/bike/img/static/uVTppaVeTsblOqJsLqEk'
                                        }}
                                        style={styles.tabBar}
                                    />
                                </TouchableOpacity>
                                <TouchableOpacity onPress={() => setIsCodeLogin(false)}>
                                    <Image
                                        source={{ uri: !isCodeLogin ? 
                                            'https://lxnapi.ccttiot.com/bike/img/static/unCWmblh1uzRcYxBzI1K' : 
                                            'https://lxnapi.ccttiot.com/bike/img/static/uqPMG4DDTpTyVg7fFV50'
                                        }}
                                        style={styles.tabBar1}
                                    />
                                </TouchableOpacity>
                            </View>
                        )}
                        {renderLoginForm()}
                    </Layout>
                </View>
            </ImageBackground>

            <Modal
                visible={modalVisible}
                backdropStyle={styles.backdrop}
                onBackdropPress={() => setModalVisible(false)}
            >
                <Card disabled style={styles.modalCard}>
                    <Text category='h5' style={styles.modalTitle}>
                        {modalConfig.title}
                    </Text>
                    <Text style={styles.modalText}>
                        {modalConfig.message}
                    </Text>
                    <Button size='large' onPress={() => setModalVisible(false)}>
                        确定
                    </Button>
                </Card>
            </Modal>
        </>
    );
};
const styles = StyleSheet.create({
    backgroundImage: {
        flex: 1,
        width: rpx(750),
        height: rpx(472),
    },
    tipTxt:{
        fontWeight: 400,
        fontSize: rpx(32),
        color: '#3D3D3D',
    },
    inputBox: {
        paddingLeft: rpx(36),
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: rpx(68),
        width: rpx(614),
        height: rpx(108),
        backgroundColor: '#EFEFEF',
        borderRadius: rpx(54),
    },
    getCode: {
        fontWeight: '400',
        fontSize: rpx(28),
        color: '#4297F3',
    },
    getCodeDisabled: {
        color: '#999',
    },
    loginBtn: {
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: rpx(68),
        width: rpx(614),
        height: rpx(108),
        backgroundColor: '#4297F3',
        borderRadius: rpx(54),
    },
    loginTxt: {
        fontWeight: '700',
        fontSize: rpx(36),
        color: '#FFFFFF',
    },
    input: {
        width: rpx(500),
        borderWidth: 0,
    },
    input2: {
        width: rpx(350),
        borderWidth: 0,
    },
    inputIcon: {
        width: rpx(38),
        height: rpx(38),
    },
    overlay: {
        flex: 1,
        marginTop: rpx(400),
        height: '100%',
        backgroundColor: '#fff',
        padding: rpx(68),
    },
    tabBarBox: {
        marginTop: rpx(42),
        flexDirection: 'row',
    },
    tabBar: {
        width: rpx(319),
        height: rpx(108),
    },
    tabBar1: {
        marginLeft: rpx(-30),
        width: rpx(319),
        height: rpx(108),
    },
    container: {
        borderRadius: rpx(16),
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
    },
    backdrop: {
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
    modalCard: {
        minWidth: rpx(500),
        padding: rpx(20),
    },
    modalTitle: {
        marginBottom: rpx(20),
        textAlign: 'center',
        fontSize: rpx(36),
        fontWeight: 'bold',
    },
    modalText: {
        marginBottom: rpx(40),
        textAlign: 'center',
        fontSize: rpx(32),
        lineHeight: rpx(48),
    },
});

export default LoginScreen;