import React, { useEffect, Fragment, useState, useCallback, useContext } from 'react';
import FindPassword from './FindPassword';
import { Linking, Alert, View, Text, Modal } from 'react-native';
import Styled from 'styled-components/native';
import { useForm } from 'react-hook-form';
import theme from '~/Themes';
import Loading from '~/Components/UIControls/Loading';
import fetchGet, { fetchPost } from '~/Utils/fetch';
import session from '~/Utils/session';
import jwtDecode from 'jwt-decode';
import { alert, MessageProvider, useToast } from '~/Components/UIControls/Message';
import { Util } from '~/Utils/utils';
import Input from '~/Components/UIControls/Input';
import Button from '~/Components/UIControls/Button';
import Checkbox from '~/Components/UIControls/Checkbox';
import { SplashContext } from '~/Components/Splash';
import { Config } from '~/Configuration';
import { PasswordChange } from './PasswordChange';
import { NotificationUtil } from '~/Utils/notificationUtil';
import { version } from '~/version';

const Container = Styled.SafeAreaView`
    flex: 1;
    background-color: #ffffff;
    align-items: center;
    justify-content: center;
`;
const FormContainer = Styled.View`
    width: 73%;
    margin-top: 50;
    margin-bottom: 54;
`;
const LoginText = Styled.Text`
    font-family: ${theme.Fonts.Medium};
    include-font-padding: false;
    font-size: 19;
    line-height: 28;
    color: #707070;
    margin-top: 7.5;
`;
const InputField = Styled(Input)`
    margin-bottom: 0px;
    height: 40px;
`;
const LoginButton = Styled(Button)`
    width: 100%;
    margin-top: 10px;
    height: 55px;
    padding: 0px;
`;
const SystemName = Styled.Text`
    font-family: ${theme.Fonts.Light};
    font-size: 12;
    line-height: 18;
    margin-top: 5;
    color: #9aa3ac;
`;
const Version = Styled.Text`
    font-family: ${theme.Fonts.Light};
    font-size: 12;
    line-height: 18;
    margin-top: 5;
    color: #9aa3ac;
`;
const Logo = Styled.Image`
    width: 107px;
    height: 30px;
`;
const LogoText = Styled.Image`
    width: 77px;
    height: 17px;
`;

const Login = (props) => {
    const splash = useContext(SplashContext);
    const navigation = props.navigation;
    const [loading, setLoading] = useState(true);
    const [dummy] = useState(Math.random());
    const [loginState, setLoginState] = useState({
        IsSaveId: true,
        IsAutoLogin: true,
        SiteId: '',
        UserId: '',
        Passwd: '',
    });
    const [passwordChange, setPasswordChange] = useState({
        change: false,
        loginData: null,
        loginResult: null,
        changedPassword: null,
        title: '',
        message: '',
        buttons: [],
    });
    const [showFindPassword, setShowFindPassword] = useState(false);
    const { showMessage } = useToast();

    useEffect(() => {
        (async () => {
            await session.load();
            const loginSite = session.getLoginSite();
            if (session.isSaveId()) {
                setLoginState({
                    ...loginState,
                    IsSaveId: session.isSaveId(),
                    IsAutoLogin: session.isAutoLogin(),
                    SiteId: Util.get(loginSite, 'SiteId'),
                    UserId: session.getSavedUserId(),
                });
            } else {
                setLoginState({
                    ...loginState,
                    IsSaveId: false,
                    IsAutoLogin: false,
                });
            }
            setLoading(false);
            splash.hide();
        })();
    }, []);

    console.log(loginState);

    const loginSuccess = async (data, result) => {
        console.log('result', result);
        console.log('siteId:', result.SiteId, ', accessToken:', result.AccessToken);

        const tokenUserInfo = jwtDecode(result.AccessToken);

        await session.setIsSaveId(data.IsSaveId, result.UserId + '');
        await session.setAutoLogin(data.IsAutoLogin);
        await session.setSiteId(result.SiteId + '');
        await session.setLoginSite({
            SiteId: result.SiteId,
            SiteName: result.SiteName,
            BuildingId: tokenUserInfo.BuildingId,
            BuildingName: tokenUserInfo.BuildingName,
            ApiSido: tokenUserInfo.ApiSido,
            ApiSigun: tokenUserInfo.ApiSigun,
        });
        await session.setAccessToken(result.AccessToken);
        await session.setUserInfo(tokenUserInfo);

        const siteConfig = await fetchGet(`api/siteconfig`);
        await session.saveSiteConfig(siteConfig);
        const menus = await fetchGet(`api/sitemap/menu/2?siteId=${result.SiteId}&userGroupId=${result.UserGroupId}`);
        await session.saveMenus(menus);
        console.log('saved menus length : ', menus.length);

        var error = await NotificationUtil.updatePushToken(result.SiteId, result.UserId);
        if (!!error) {
            showMessage('푸시알림 등록실패 : ' + error);
        }

        navigation.navigate('MainNavigator');
    };

    const onSubmit = async (data) => {
        if (!data) data = loginState;
        console.log('data', data);
        if (data.SiteId == '') {
            alert('SITE ID', 'SITE ID 를 입력하세요.');
            return;
        }
        if (data.UserId == '') {
            alert('USER ID', 'USER ID 를 입력하세요.');
            return;
        }
        if (data.Passwd == '') {
            alert('PASSWORD', 'PASSWORD 를 입력하세요.');
            return;
        }

        setLoading(true);
        try {
            const result = await fetchPost('api/app/users/signin', data);

            if (data.PasswordReset) {
                setPasswordChange({
                    change: true,
                    loginData: { ...data },
                    loginResult: { ...result },
                    changedPassword: null,
                    title: '비밀번호 변경',
                    message: '비밀번호가 초기화 되었습니다. 비밀번호를 변경하세요.',
                    buttons: [
                        {
                            type: 'change',
                            onPress: async () => {
                                await loginSuccess(data, result);
                            },
                        },
                        {
                            type: 'cancel',
                            onPress: async () => {
                                setPasswordChange({
                                    ...passwordChange,
                                    change: false,
                                    loginData: null,
                                    loginResult: null,
                                    changedPassword: null,
                                });
                            },
                        },
                    ],
                });
            } else if (data.UserId == data.Passwd) {
                setPasswordChange({
                    change: true,
                    loginData: { ...data },
                    loginResult: { ...result },
                    changedPassword: null,
                    title: '최초 비밀번호 변경',
                    message: '처음 로그인 입니다. 비밀번호를 변경하세요.',
                    buttons: [
                        {
                            type: 'change',
                            onPress: async () => {
                                await loginSuccess(data, result);
                            },
                        },
                        {
                            type: 'cancel',
                            onPress: async () => {
                                setPasswordChange({
                                    ...passwordChange,
                                    change: false,
                                    loginData: null,
                                    loginResult: null,
                                    changedPassword: null,
                                });
                            },
                        },
                    ],
                });
            } else if (result.IsChangePassword) {
                setPasswordChange({
                    change: true,
                    loginData: { ...data },
                    loginResult: { ...result },
                    changedPassword: null,
                    title: '비밀번호 변경',
                    message: '3개월간 비밀번호를 변경하지 않았습니다. 비밀번호를 변경해주십시오.',
                    buttons: [
                        {
                            type: 'change',
                            onPress: async () => {
                                await loginSuccess(data, result);
                            },
                        },
                        {
                            type: 'cancel',
                            onPress: async () => {
                                setPasswordChange({
                                    ...passwordChange,
                                    change: false,
                                    loginData: null,
                                    loginResult: null,
                                    changedPassword: null,
                                });
                            },
                        },
                        {
                            text: '다음에변경',
                            onPress: async () => {
                                await loginSuccess(data, result);
                                setPasswordChange({
                                    ...passwordChange,
                                    change: false,
                                    loginData: null,
                                    loginResult: null,
                                    changedPassword: null,
                                });
                            },
                        },
                    ],
                });
            } else {
                await loginSuccess(data, result);
            }
            setLoading(false);
        } catch (error) {
            console.log(error);
            setLoading(false);
            showMessage(error.message);
        }
    };

    return (
        <Fragment>
            <Container>
                <Logo
                    source={{
                        uri: `${Config.BASE_URL}/files/static/app_login_title.png?dummy=${dummy}`,
                        headers: { Pragma: 'no-cache' },
                        cache: 'reload',
                    }}
                />
                <LoginText>현장 관리자 로그인</LoginText>
                <FormContainer>
                    <InputField
                        placeholder="SITE ID"
                        placeholderTextColor="#0b83e6"
                        leftSvg="/login/siteid"
                        style={{ marginBottom: 10, borderWidth: 1, borderColor: '#0b83e6' }}
                        defaultValue={loginState.SiteId}
                        inputStyle={{ textAlign: 'center', color: '#0b83e6' }}
                        onChangeText={(text) => {
                            setLoginState({ ...loginState, SiteId: text });
                        }}
                    />
                    <InputField
                        placeholder="USER ID"
                        placeholderTextColor="#b9bac4"
                        leftSvg="/login/userid"
                        style={{ marginBottom: 10, borderWidth: 1, borderColor: '#dedede' }}
                        defaultValue={loginState.UserId}
                        inputStyle={{ textAlign: 'center', color: '#707070' }}
                        onChangeText={(text) => {
                            setLoginState({ ...loginState, UserId: text });
                        }}
                    />
                    <InputField
                        placeholder="PASSWORD"
                        secureTextEntry={true}
                        leftSvg="/login/password"
                        placeholderTextColor="#b9bac4"
                        style={{ borderWidth: 1, borderColor: '#dedede' }}
                        inputStyle={{ textAlign: 'center', color: '#707070' }}
                        onChangeText={(text) => {
                            setLoginState({ ...loginState, Passwd: text });
                        }}
                    />

                    <View style={{ marginTop: 10, flexDirection: 'row' }}>
                        <Checkbox
                            label="아이디저장"
                            style={{ marginRight: 20 }}
                            value={loginState.IsSaveId}
                            hasState={false}
                            labelStyle={{ fontFamily: theme.Fonts.Regular, fontSize: 16, lineHeight: 25 }}
                            onChange={(checked) => {
                                const nextState = { ...loginState, IsSaveId: checked };
                                console.log('change saveid - ', nextState);
                                setLoginState(nextState);
                            }}
                        />
                        <Checkbox
                            label="로그인유지"
                            value={loginState.IsAutoLogin}
                            hasState={false}
                            labelStyle={{ fontFamily: theme.Fonts.Regular, fontSize: 16, lineHeight: 25 }}
                            onChange={(checked) => {
                                const nextState = { ...loginState, IsAutoLogin: checked };
                                console.log('change isautologin - ', nextState);
                                setLoginState(nextState);
                            }}
                        />
                    </View>
                    <View>
                        <Button
                            onPress={() => {
                                setShowFindPassword(true);
                            }}
                            color="grey"
                            textStyle={{ fontSize: 16 }}
                            buttonStyle={{ height: 'auto', width: 'auto', paddingHorizontal: 10, paddingVertical: 2 }}
                        >
                            ID/PW 찾기
                        </Button>
                    </View>
                    <LoginButton
                        textStyle={{ fontFamily: theme.Fonts.Medium, fontSize: 22, lineHeight: 33 }}
                        onPress={() => {
                            onSubmit();
                        }}
                    >
                        LOGIN
                    </LoginButton>
                </FormContainer>

                <SystemName>Facility Management System</SystemName>
                <Version>Ver. {version}</Version>
            </Container>
            {loading && <Loading />}
            <Modal visible={passwordChange.change} transparent={true} animationType="fade">
                <PasswordChange
                    loginData={passwordChange.loginData}
                    loginResult={passwordChange.loginResult}
                    title={passwordChange.title}
                    message={passwordChange.message}
                    buttons={passwordChange.buttons}
                />
                <MessageProvider />
            </Modal>
            <Modal visible={showFindPassword} transparent={true} animationType="fade">
                <FindPassword
                    closeHandler={() => {
                        setShowFindPassword(false);
                    }}
                    completeHandler={(data) => {
                        setShowFindPassword(false);
                        setLoginState({
                            ...loginState,
                            SiteId: data.SiteId,
                            UserId: data.UserId,
                            Passwd: data.UserId,
                            PasswordReset: true,
                        });
                        onSubmit({
                            ...loginState,
                            SiteId: data.SiteId,
                            UserId: data.UserId,
                            Passwd: data.UserId,
                            PasswordReset: true,
                        });
                    }}
                />
            </Modal>
        </Fragment>
    );
};

Login.navigationOptions = {
    headerShown: false,
    title: 'Login',
    headerTransparent: true,
    headerTintColor: '#e70915',
    headerTitleStyle: {
        fontWeight: 'bold',
    },
};

export default Login;
