import '../../cmp/field/LabeledField.jsx';
import Button from '../../cmp/button/Button.jsx';
import Logo from '../../../svg/logo_vkusvill.svg';
import './loginPage.scss';

import LoginHelp from './LoginHelp.jsx';
import LoginPhone from './LoginPhone.jsx';
import LoginCode from './LoginCode.jsx';
import { AsyncAuthAjax } from "../../../controller/Ajax";
import { API } from "../../../dict/Consts";

const {AND, OR, IF} = Store;
const Login = D.declare('view.page.Login', () => {
    const initialState = {
        phone: '79999877415',
        code: '',
        codeValid: false,
        active: 'enterPhone',
        phoneValid: false,
        phoneChecking: false,
        phoneError: false,
        phoneErrorText: '',
        incorrectPhone: false,
        displayHelpPage: false,
        codeError: false
    };

    const loginStore = new Store(
      Object.assign({}, initialState)
    );

    store.sub('account.token', async function(data){
        if(!data){
            let phone = store.get('account.phone') || loginStore.get('phone') || initialState.phone;
            ACTION.NAVIGATE.execute( 'Login' );

            loginStore.set(initialState);
            loginStore.set({phone})
        }else{
            const result = await AsyncAuthAjax.get( API.ENDPOINTS.GET_USER( store.get( 'account.userID' ) ) );
            if(store.get('account.data') &&
                store.get('navigation.current') !== 'Login'){

            }else{
                store.set( 'account.data', result );
                if( result.lastLoginAt ){
                    ACTION.NAVIGATE.execute( 'Account' );
                }else{
                    ACTION.NAVIGATE.execute( 'Welcome' );
                }
            }
        }
    });

    return <div className={"login-page"}>
        <div class="login-page__big-logo">
            <Logo width="660" height="300"/>
        </div>

        <IF condition={loginStore.valTrue('displayHelpPage')}>
            <LoginHelp loginStore={loginStore}/>
        </IF>

        <IF condition={loginStore.valFalse('displayHelpPage')}>
            <h1 className="login-page__title">Добро пожаловать в&nbsp;развивающую платформу Вкусвилл!</h1>
            <form action="#" method="post" className="authorization-form">
                <Switch store={loginStore} key='active' content={{
                    enterPhone: <LoginPhone loginStore={loginStore}/>,
                    enterCode: <LoginCode loginStore={loginStore}/>
                }}/>
                <Button onClick={() => loginStore.set('displayHelpPage', true)} type={"button"}>Проблемы с авторизацией?</Button>
            </form>
        </IF>
    </div>
});
Login.route = new Route('/login');
export default Login;
export {Login};
