import Button from "/view/cmp/button/Button.jsx";
import { AsyncAjax } from "/core/Ajax.jsx";
import { API } from "/dict/Consts.jsx";
import Arr  from '/svg/arr.svg';
import { AsyncAuthAjax } from "../../../controller/Ajax";

const {AND, OR, IF} = Store;
const LoginCode = D.declare('view.page.LoginCode', ({loginStore}) => {
  const checkCode = async function () {
    loginStore.set('codeChecking', true);
    loginStore.set('codeError', false);
    try{
      // TODO: GET AUTH TOKEN. SOMEHOW
      const result = await AsyncAjax.post( API.ENDPOINTS.CHECK_PHONE(), {
        phone: loginStore.get('phone')
      } );
      store.set('account.token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE1ODA0OTQwNTgsImV4cCI6MTU4MDU4MDQ1OCwicm9sZXMiOlsiUk9MRV9BRE1JTiIsIlJPTEVfRU1QTE9ZRUUiXSwicGhvbmUiOiI3OTk5OTg3NzQxNCIsImlkIjo1fQ.W3_nAZDaZ_4PY1uIMDWjslYc33cIfT7pAIxBsugmlbPx94sl1QLRg_KemRST08PWTXyZfo9gEQ1zYOS5yICz5yo5eFF6FYyKvZ0ZNonVp17aTfVR1HiGM2V0nGbVPcfUhxNqKlVXjSsQAS_z0aX_p2K1f9HCPWE4S9FAdbbOU-NWKwcDwoGV4A9NO5jt-yZ1xzBIpj8r4Ia_eU_SU4zqQMPzYwz5LMr0oL3Zo7dzsTzEJLNwZL7xzFvzRlEJAmhfn1KZOiAPicVEqL3Vxp8Yk-KXQisIplbrR5DlU_vaxcdBeDmt2jO2Ifj2_N97MxZ8cHdF0DQPOSScU20Wz96slh8B0SXtNgEbENL2AhDaVbZPJdXVCK2dr88VNXIohM5cicm8AglknbVG3lYVgbEG9QgSmHOEw6OLQYhp3hnXbm0_pk9S6b_5zozzBQ-f0b6cbkuXH6HUBNhZyZfBLNNU-jElRod8OMd6FFIHaYU8y7SLDDRlF0IQxVgezT5g-tjeSDKLuBr6Bc0yNnNAyad1UBMIHWB4yEXuW7CWai1Qg3k35LqU-Kz2KisRkKuwjj8dj7zB2v0d3wNWqeSX-C_irL2ZAcLr4iNK_bQBuJvH64G1U4Peh22tyrqpMHkdRXcx649wfiZ0bmXk1ldM3feDhoh-BQpSP7ARIZ0J_Gc-IY4')
    }catch(e){
      loginStore.set('codeChecking', false);
      loginStore.set('codeError', true);
    }
  };
  loginStore.sub('code', function (code) {
    loginStore.set('codeValid', (code+'').length === 6);
  });

  return <>
      <view.cmp.field.LabeledField required label={'Введите код из СМС'}
        placeholder={'Код'} type={'number'}
        disabled={loginStore.valTrue('codeChecking')}
        bind={loginStore.bind('code')}
        invalid={loginStore.valTrue('codeError')}>
          <IF condition={loginStore.valTrue('codeError')}>
              <span className={"field__error-message"}>Некорректный код. Попробуйте еще раз</span>
          </IF>
      </view.cmp.field.LabeledField>

      <Button class={"button button--primary authorization-form__button"}
        type={"button"} onclick={checkCode}
        disabled={OR(
          loginStore.valFalse('codeValid'),
          loginStore.valTrue('codeChecking')
        )}>
          <span>Далее</span><Arr width="17" height="11"/>
      </Button>
  </>
});

export default LoginCode;
export {LoginCode};