import {
    View,
    Text,
    Image,
    StyleSheet,
    Pressable,
    Alert,
    Dimensions,
    ActivityIndicator,
    ScrollView,
    Switch
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import Logo from '../../../global/logo';
import NormalButton from '../../../global/normal_button';
import NormalInput from '../../../global/normal_input';
import { useEffect, useState } from 'react';
import { useAuth } from '../../../../context/AuthProvider';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Checkbox from 'expo-checkbox';
import { router } from 'expo-router';
import PhoneInput from '../../../global/phone_input';
import LanguageSwitcher from './languageSwitcher';
import { useTranslation } from '../../../../util/hooks/useTranslation';
type LoginPageProps = {
    goToNextPage: () => void;
    goToForgetPassWordPage: () => void;
    goToBindingPhoneNumberPage: () => void;
};

const screenHeight = Dimensions.get('window').height;

const LoginPage: React.FC<LoginPageProps> = ({ goToNextPage, goToForgetPassWordPage, goToBindingPhoneNumberPage }) => {
    const { t, ready, currentLanguage } = useTranslation();
    // const [loginEmail, setLoginEmail] = useState('');
    const [loginPhone, setLoginPhone] = useState('');
    const [loginPassword, setLoginPassword] = useState('');
    const [saveAccount, setSaveAccount] = useState(false);
    const [userTerms, setUserTerms] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const { login } = useAuth();
    const [isChecked, setChecked] = useState(false);
    const [showPassword, setShowPassword] = useState(false);

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

    const loadSavedCredentials = async () => {
        try {
            const savedPhone = await AsyncStorage.getItem('savedPhone');
            // const savedEmail = await AsyncStorage.getItem('savedEmail');
            const savedPassword = await AsyncStorage.getItem('savedPassword');
            if (savedPhone && savedPassword) {
                // setLoginEmail(savedEmail);
                setLoginPhone(savedPhone);
                setLoginPassword(savedPassword);
                setSaveAccount(true);
                setUserTerms(true);
                setChecked(true);
            }
        } catch (error) {
            console.error('Error loading saved credentials:', error);
        }
    };
    const _login = async (username: string, password: string) => {
        setIsLoading(true);
        if (username === '' || password === '') {
            Alert.alert(t('login.alert.pleaseEnter'));
        } else if (username.includes('@')) {
            Alert.alert(t('login.alert.binding'), t('login.alert.binding1'), [
                { text: t('login.alert.binding2'), onPress: () => goToBindingPhoneNumberPage() },
                { text: t('login.alert.binding3'), onPress: () => router.replace('/login') }
            ]);
        } else {
            if (userTerms) {
                const isBinding = false;
                const response = await login(username, password, isBinding);
                if (response) {
                    if (saveAccount) {
                        await AsyncStorage.setItem('savedPhone', username);
                        await AsyncStorage.setItem('savedPassword', password);
                    } else {
                        await AsyncStorage.removeItem('savedPhone');
                        await AsyncStorage.removeItem('savedPassword');
                    }

                } else {
                    Alert.alert(t('login.alert.error'), `${t('login.alert.reason')}`);
                }
            } else {
                Alert.alert(t('login.alert.agree'));

            }
            
        }
        setIsLoading(false);
    };
    const goToUserTermsPage = () => {
        router.push('(public)/userTermsPage');
    };

    return (
        <ScrollView
            contentContainerStyle={{ flexGrow: 1, justifyContent: 'center' }}
            keyboardShouldPersistTaps="handled"
            className={`flex-1   ${screenHeight < 750 ? '' : 'space-y-8'}`}
        >
            <LanguageSwitcher></LanguageSwitcher>
            <View className="flex-1 py-3">
                <View className="items-center">
                    {/* <View className="flex-3 items-center  justify-end" style={{}}> */}
                    <Image
                        source={require('../../../../assets/ccLogo.png')}
                        resizeMode="contain"
                        style={{
                            width: screenHeight > 750 ? 250 : 180,
                            height: screenHeight > 750 ? 250 : 180
                        }}
                    />
                </View>
                <View
                    style={{
                        gap: 8
                        // paddingBottom: Math.max(insets.bottom, 20)
                        // marginTop: screenHeight > 750 ? 40 : 0
                    }}
                    className="mx-[5%] mt-3"
                >
                    <Text className="text-lg text-center text-[#888888] font-[500]">
                        {t('login.tip1')}<Text className="font-bold"> {t('login.tip2')} </Text>{t('login.tip3')}
                    </Text>
                    <Pressable onPress={goToBindingPhoneNumberPage}>
                        <Text className="text-xl text-center text-[#02677D] font-[800] underline">
                            {t('login.binding')}
                        </Text>
                    </Pressable>

                    <PhoneInput
                        value={loginPhone}
                        onChangeText={(phone) => setLoginPhone(phone)}
                        placeholder={t('login.phone')}
                        extendedStyle={{ borderRadius: 12, padding: 20 }}
                        textContentType="telephoneNumber"
                        autoComplete="tel"
                        keyboardType="phone-pad"
                        autoCapitalize="none"
                    />
                    <View className="relative">
                        <NormalInput
                            value={loginPassword}
                            placeholder={t('login.password')}
                            onChangeText={(password) => setLoginPassword(password)}
                            secureTextEntry={!showPassword}
                            extendedStyle={{ borderRadius: 12, padding: 20, paddingRight: 50 }}
                            textContentType="password"
                            autoComplete="password"
                        />
                        <Pressable
                            className="absolute right-4 top-0 bottom-0 flex justify-center"
                            onPress={() => setShowPassword(!showPassword)}
                        >
                            <Ionicons
                                name={showPassword ? 'eye-outline' : 'eye-off-outline'}
                                size={24}
                                color="#02677D"
                            />
                        </Pressable>
                    </View>

                    <View className="flex flex-row items-center ">
                        <Checkbox
                            style={styles.checkbox}
                            value={saveAccount}
                            color={saveAccount ? '#02677D' : '#02677D'}
                            onValueChange={(newValue) => {
                                setSaveAccount(newValue);
                            }}
                        />

                        <Text style={styles.text}>{t('login.rememberPhone')}</Text>
                        
                    </View>
                    <View className="flex flex-row items-center">
                        <Checkbox
                            style={styles.checkbox}
                            value={userTerms}
                            color={userTerms ? '#02677D' : '#02677D'}
                            onValueChange={(newValue) => {
                                setUserTerms(newValue);
                            }}
                        />

                        <Text style={styles.text}>{t('login.termsofService')}
                            <Text style={styles.userTerms} onPress={goToUserTermsPage}>{t('login.termsofService1')}</Text>
                        </Text>
                    </View>

                    <NormalButton
                        extendedStyle={{ padding: 20 }}
                        onPress={() => _login(loginPhone, loginPassword)}
                        title={
                            isLoading ? (
                                <Text
                                    style={{
                                        fontWeight: '700',
                                        fontSize: 20,
                                        color: '#fff'
                                    }}
                                >
                                    <ActivityIndicator />
                                </Text>
                            ) : (
                                <Text
                                    style={{
                                        fontWeight: '700',
                                        fontSize: 20,
                                        color: '#fff'
                                    }}
                                >
                                    {t('login.signIn')}
                                </Text>
                            )
                        }
                    />
                    <View className="flex flex-row justify-between relative">
                        <Pressable className="self-start" onPress={goToNextPage}>
                            <Text style={styles.text}>{t('login.register')}</Text>
                        </Pressable>
                        <Pressable className="self-start" onPress={() => goToForgetPassWordPage()}>
                            <Text style={styles.text}>{t('login.forgotPassword')}</Text>
                        </Pressable>
                    </View>
                </View>
                <View className="pb-6" />
            </View>
        </ScrollView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        height: Dimensions.get('window').height,
        justifyContent: 'center',
        marginHorizontal: 20
    },
    topContainerForLogo: {},
    checkbox: {
        marginLeft: 8,
        marginRight: 8
    },
    text: {
        color: '#02677D',
        fontSize: 16,
        paddingVertical: 5
    },
    userTerms: {
        color: '#02677D',
        fontSize: 16,
        paddingVertical: 5,
        textDecorationLine: 'underline'

    }
});
export default LoginPage;
