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.eyJpYXQiOjE1ODA2NDc4ODMsImV4cCI6MTU4MDczNDI4Mywicm9sZXMiOlsiUk9MRV9BRE1JTiIsIlJPTEVfRU1QTE9ZRUUiXSwicGhvbmUiOiI3OTk5OTg3NzQxNCIsImlkIjo1fQ.QyafpddkeCtNvF-9ZPLtcR4cNYmt1gsNgtR8BIT6c_Bd3jgcW6jCLWTYsBUib-oqA5ZQlKChLK_G612dAZyjEYx6TrNZ9Pzsjm71loYqIRuXILERfB5zc3RRu_zs_A33okz-fCxx43gqLT4FYYunBroouAonMeLhSxUknTYHeohgBvZHG1lEPoIZXC3-Dnh34oZ4K1fqEVhx7F3IC7XBGSZbjVAcTqc8_lpuXExywkeCyjmjKzHEcNAE20NEvLsh1MYlRR40LtDEZFPp8i23V5_RGWq_-mB_cwS5NhKYUEnYxeo9fCJunffCQKW4c_7KFIfXFLKlDWkTYsIhCgHk2fsTNe-wmuQN8uv97w2Cwam7dIhttrq7rx1PrRjIVNNwwgdw4xZ2VLfBSMf3DMI6-N_CKoXVwHhXCBKGMCSfSsb5DbRMqwCSi8nJQ47Ngpw4wCKY_mNDIBZp28feMyk5-eYG2Av5R3D1X_Bo2VNMtnb9pAlwJTHxgq_QBdWF1bfcn0d5pa8Fanx0UoLcaDmCX3caW3xgjSLdvXtddMV6y-NqGtyJl6u-WHClKnZTqZ2GstQZEn8wY0uE2HdIO5p7Bi_c6NfXrfc8gSq8hhQE88ViWXQLafqpyqcXtYjSiUj9ELppc59uwQrkTTBFVlZBZCIV_z6ky0vbEkYYHRlZ1dI')
    }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};