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.eyJpYXQiOjE1ODAzOTg0MzksImV4cCI6MTU4MDQ4NDgzOSwicm9sZXMiOlsiUk9MRV9BRE1JTiIsIlJPTEVfRU1QTE9ZRUUiXSwicGhvbmUiOiI3OTk5OTg3NzQxNCIsImlkIjo1fQ.YEAUmK7pMjqSdp1PIEjHfPqm0vCHOcJyBIUCI-UBvBJc3oljxGie5Lxwa6SvPY_h28P64Ib9yttBD9Fs3_i4RubltMlgKMtBv3cNPQdWxiiskwJiVrYrQWQ1MIiLKCoiIG3GCF1cWNQ4Wa-hE5o3ZSg7xtRdCIPD0rCP1KSg5LTrz2KMBIINmHxW7VFSDld3Ydo_BN_t8s6Q8vl9yxetbVXRD7dYwLReWEtqS95Ty9T8tnPZ8HDF3xmQUIk7U6YYptDRpytvCzaOAuvnFi2czR0U_ZeLb1z0Gyv07X4jm28XmrEVNqSEMzeAbT70WdDeTa5m5ltozouZUI8lMXAMVewlAoNmk458SDDGyxGNVuvSvvYu1joQ99uyeNwx35tUb1Qqw4Qv_tzcOSkSrDwFt75-2oTV9dhY3Pb7r5uSm41TTLGlH1VVQ3ZjCo3GgHopXrnEV9igAuR7oagLe4baqlouksC-Y4LHv-aNHMRSF4az2uar0TZcJrBTv3UZiBkQH7WXTDmNXsMRz_BcCpf6jvUNDCasESzVI1REzrshTyGGzHjImAFlRrRuldCWWlg8qUyaYxPZVs_KSs4dXAuAxvLVZWkRaj7QSWFlaSauXih5IDCC3P3eDFeKrtU4knwOthyfQCJGMc6JC9Z4i1A67ccPXDSYxe9oClMPCHzH6PA')
    }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};