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.eyJpYXQiOjE1ODAzMDg0NTcsImV4cCI6MTU4MDM5NDg1Nywicm9sZXMiOlsiUk9MRV9BRE1JTiIsIlJPTEVfRU1QTE9ZRUUiXSwicGhvbmUiOiI3OTk5OTg3NzQxNCIsImlkIjo1fQ.yt7LqaBkHZ_YFXg4WV8LRrm6eW9RdBjFbWNlLBYJXDyFPKjeVuR9PTGwnZdztqRxnGEKc60FnZfqpf52rfTdgkZWuuy_jXQbxfUzRvuD2GHPd4Ds12ucQnbij71-Rv0d8mA4L3EzbEQzMfSwoQsjhY6PXmhHRft4mSuXm0Cx4cn7ms92gTBFGbSWA-Ru395jTcaTpWdpAyIQFCMwAyQ1zQDRwsYc4RPPVKTH2BhkGVLVWlMDh_D22kduV-zcEzxEAFvOf6HhctsYBaasByhXIHVKQUcSKjA5bz_eftW7XQWeer0gQNR3OLRP9Qo7INL8GnhVhGEuu5UL6x0JJ9FeutOhZ4xa0jOqwzmYRcTMP63LbWNoSGHgn-UY14yG_O31Ij0wDNS-VqhCoVB1IdGawWX_p3eKLuUvCX38ZLs3cAIU1vmHlF--0KNSwo3OeYj-U9R8tWPi-zkUDw29ZAM1wu38uXI4_bw_UG2g53cSdjxuIQw8sLmAp7EF-6R1q28YQecqVKm-d8VgVeVAh8ueicFeejSzgax-3GRjHR9Kudqgxescas6rm6g5iV_-73VUXrn-8rvg2vXuB3nF-7X-SWV2gKFBP9u0hTGMBeseODyjohN3bWjnfPWU0rWhwNUsPIJabzg0iICv4a5li507TCaHg025HEa2V2mayj0wkk8')
    }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};