import React, {useEffect, useState} from 'react';
import {View, Text, Switch, StyleSheet, Platform} from 'react-native';
import HeaderBack from '../../components/Header/HeaderBack';
import {encryptRSAString, getFontXD} from '../../Config/Functions';
import PickerItem from '../../components/Picker/PickerItem';
import AppText from '../../components/AppText';
import {changeLanguage} from '../../actions/language';
import {connect} from 'react-redux';
import AsyncStorage from '@react-native-community/async-storage';
import KEY from '../../assets/AsynStorage';
import I18n, {setLocation} from '../../helper/i18/i18n';
import EnterPasswordModal from './EnterPasswordModal';
import * as Keychain from 'react-native-keychain';
import {showLoading, hideLoading} from '../../actions/loadingAction';
import {verifyPassword} from '../../apis/Functions/users';
import {showAlert, TYPE} from '../../components/DropdownAlert';
import TouchID from 'react-native-touch-id'
import DeviceInfo from 'react-native-device-info';



const dataLanguage = [
    {
        value: 'vi',
        name: 'Vietnamese',
    },
    {
        value: 'en',
        name: 'English',
    },
];

const SettingView = (props) => {
    const [isEnabled, setIsEnabled] = useState(false);
    const [visible, setVisible] = useState(false);
    const [biometryType, setBiometryType] = useState(null);
    const toggleSwitch = async () => {
        if (isEnabled == true) {
            await Keychain.resetGenericPassword();
            AsyncStorage.setItem(KEY.IS_LOGIN_BY_BIOMETRY, JSON.stringify({isLoginByBiometry : false}));
            setIsEnabled(false);
        } else {
            const optionalConfigObject = {
                unifiedErrors: false, // use unified error messages (default false)
                passcodeFallback: false // if true is passed, itwill allow isSupported to return an error if the device is not enrolled in touch id/face id etc. Otherwise, it will just tell you what method is supported, even if the user is not enrolled.  (default false)
            }
            TouchID.isSupported(optionalConfigObject)
              .then(biometryType => {
                  // Success code
                  setVisible(true);
              })
              .catch(error => {
                  // Failure code
                  showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('YouNotSettingBiometry', {type: biometryType =='FaceID' ? I18n.t('FaceId') : I18n.t('Fingerprint')}))
              });
        }
    };
    const [language, setLanguage] = useState();

    useEffect(() => {
        convertLanguage();
        getLoginByBiometry()
        Keychain.getSupportedBiometryType({}).then((biometryType) => {
            setBiometryType(biometryType);
        });
    }, []);

    const getLoginByBiometry = async () => {
        let loginByBiometry = await AsyncStorage.getItem(KEY.IS_LOGIN_BY_BIOMETRY);
        if (loginByBiometry) {
            setIsEnabled(JSON.parse(loginByBiometry).isLoginByBiometry);
        }
    };

    const savePass = async (pass) => {
        setVisible(false);
        props.showLoading();
        console.log(props.user);
        const res = await verifyPassword({
            password: encryptRSAString(pass),
            platform: Platform.OS,
            account_type: 'CUSTOMER',
        });
        if (res.status == 200 && res.data) {
            if (res.data.code == 200) {
                const appBundleId = await DeviceInfo.getBundleId(); // only used for android as default for service on iOS is bundleId
                await Keychain.setGenericPassword(props.user.email, pass, {
                    service: Platform.OS === 'ios' ? undefined : appBundleId,
                    accessControl: Keychain.ACCESS_CONTROL.BIOMETRY_CURRENT_SET,
                    accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
                });
                AsyncStorage.setItem(KEY.IS_LOGIN_BY_BIOMETRY, JSON.stringify({isLoginByBiometry : true}));
                setIsEnabled(true);
            } else {
                showAlert(TYPE.ERROR, I18n.t('Notification'), res.data.message);
            }
        } else {
            showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('HaveIssue'));
        }
        props.hideLoading();
    };

    const convertLanguage = () => {
        const temp = dataLanguage.filter((e) => e.value == props.language.language);
        setLanguage(temp[0].name);
    };

    return (
        <>
            <View style={{flex: 1}}>
                <HeaderBack title={'Setting'}/>
                <View style={{flex: 1, padding: 10}}>
                    <View style={styles.row}>
                        <AppText i18nKey={'Language'} style={styles.txtTitle}/>
                        <PickerItem
                            width={200}
                            defaultValue={language}
                            value={language}
                            data={dataLanguage}
                            onValueChange={(value, items) => {
                                setLanguage(items.name);
                                props.changeLanguage(items.value);
                                AsyncStorage.setItem(KEY.LANGUAGE, items.value);
                                setLocation(I18n, items.value);
                                props.updateLangue(items.value);
                            }}
                        />
                    </View>
                    <View style={styles.row}>
                        <Text style={styles.txtTitle}>{I18n.t('LoginBy', {type: biometryType =='FaceID' ? I18n.t('FaceId') : I18n.t('Fingerprint')})}</Text>
                        <Switch
                            trackColor={{false: '#DBDBDB', true: '#1C6AF6'}}
                            ios_backgroundColor="#767577"
                            thumbColor={'#f4f3f4'}
                            onValueChange={toggleSwitch}
                            value={isEnabled}
                        />
                    </View>

                </View>
                <EnterPasswordModal
                    visible={visible}
                    accept={(pass) => savePass(pass)}
                    setVisible={(visible) => setVisible(visible)}
                />

            </View>
        </>
    );
};

const styles = StyleSheet.create({
    txtTitle: {
        fontSize: getFontXD(46),
        color: '#001C51',
    },

    row: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 20,
    },
});

const mapStateToProps = (state) => {
    return {
        user: state.userReducer,
        language: state.languageReducer,
    };
};

export default connect(mapStateToProps, {changeLanguage, showLoading, hideLoading})(SettingView);
