const localeCookieName = 'loginPageLocale';
const defaultLocale = 'en';
const locales = [
  { icon: '🇪🇳', name: '🇪🇳 Eng', value: 'en', language: 'en' },
  {
    icon: '🇭🇰',
    name: '🇭🇰 繁體',
    value: 'zh-TW',
    language: 'zh',
    country: 'TW',
  },
  {
    icon: '🇨🇳',
    name: '🇨🇳 简体',
    value: 'zh-CN',
    language: 'zh',
    country: 'CN',
  },
];

const loadI18n = (locale, callback) => {
  Ext.Ajax.request({
    url: `/static/public/i18n/${locale}.json`,
    callback: function (opts, success, response) {
      if (success) callback(Ext.decode(response.responseText));
      else callback();
    },
  });
};

Ext.define('LoginPanel', {
  extend: 'Ext.panel.Panel',
  height: '100vh',

  layout: {
    type: 'vbox',
    align: 'center',
    pack: 'center',
  },

  style: {
    'background-image': 'url(/static/public/images/login1.png)',
    'background-size': 'cover',
    'background-position': '50% 75%',
    opacity: '0.8',
  },
  bodyStyle: {
    'background-color': 'transparent',
  },
  params: {
    locale: defaultLocale,
  },
  viewModel: {
    data: {
      i18n: {},
    },
  },
  getI18n: function (key) {
    const i18n = this.getViewModel().get('i18n');
    if (key) return _.get(i18n, key, key);
    else return i18n;
  },
  changeLocale: function (language, country, locale) {
    const me = this;
    me.setLoading(true);
    loadI18n(locale, function (i18n) {
      if (i18n) {
        me.getViewModel().set('i18n', i18n);
        Ext.util.Cookies.set(localeCookieName, locale);
      } else {
        App.showWarning(`No ${locale}`);
      }

      me.down('#username').setFieldLabel(`<p style=font-size:28px>${me.getI18n('LOGIN.username')}:</p>`);
      me.down('#password').setFieldLabel(`<p style=font-size:28px>${me.getI18n('LOGIN.pw')}:</p>`);
      me.down('#locale').setFieldLabel(`<p style=font-size:28px>${me.getI18n('LOGIN.locale')}:</p>`);
      me.down('#btn1').setText(`<p style=font-size:24px>${me.getI18n('LOGIN.forgotPassword')}</p>`);
      me.down('#btn2').setText(`<p style=font-size:24px>${me.getI18n('LOGIN.login')}</p>`);
      me.down('#title').setTitle(`<p style=font-size:28px>${me.getI18n('LOGIN.login')}</p>`);

      me.setLoading(false);
    });
  },
  login: function () {
    const me = this,
      f = me.down('form'),
      values = f.getValues();
    if (f.isValid()) {
      f.setLoading(true);
      Ext.Ajax.request({
        method: 'POST',
        url: '/login',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        params: values,

        callback: function (opts, success, response) {
          if (success) {
            window.location.reload();
          } else {
            let msg;
            if (response.status === 401) {
              msg = me.getI18n('LOGIN.wrongPw');
            } else if (response.status === 403) {
              msg = me.getI18n('LOGIN.acNotAvailable');
            } else {
              msg = me.getI18n('LOGIN.fail');
            }

            iziToast.show({
              message: msg,
              color: 'yellow',
              icon: 'fas fa-exclamation-circle',
              iconColor: '#f1c40f',
              progressBarColor: '#f1c40f',

              timeout: 5000,

              resetOnHover: true,
              close: false,
              closeOnClick: true,

              transitionIn: 'fadeInDown',
              transitionOut: 'fadeOutUp',

              position: 'topCenter',
            });
            f.setLoading(false);
          }
        },
      });
    }
  },
  forgetPassword: function () {
    const me = this,
      f = me.down('form'),
      values = f.getValues();

    if (!_.isEmpty(values.username)) {
      f.setLoading(true);
      Ext.Ajax.request({
        method: 'POST',
        url: '/public/forget-pw',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        params: { username: values.username },

        callback: function (opts, success, response) {
          if (success) {
            // TODO: nee to change the i18n
            iziToast.show({
              message: me.getI18n('MSG.newPwSentToUserEmail'),
              color: 'green',
              icon: 'fas fa-check',
              iconColor: '#07bc0c',
              progressBarColor: '#07bc0c',
              timeout: 5000,
              resetOnHover: true,
              close: false,
              closeOnClick: true,
              transitionIn: 'fadeInDown',
              transitionOut: 'fadeOutUp',
              position: 'topCenter',
            });
          } else {
            let msg;
            if (response.status === 401) {
              msg = me.getI18n('LOGIN.wrongPw');
            } else if (response.status === 403) {
              msg = me.getI18n('LOGIN.acNotAvailable');
            } else {
              msg = me.getI18n('LOGIN.fail');
            }

            iziToast.show({
              message: msg,
              color: 'yellow',
              icon: 'fas fa-exclamation-circle',
              iconColor: '#f1c40f',
              progressBarColor: '#f1c40f',

              timeout: 5000,

              resetOnHover: true,
              close: false,
              closeOnClick: true,

              transitionIn: 'fadeInDown',
              transitionOut: 'fadeOutUp',

              position: 'topCenter',
            });
          }
          f.setLoading(false);
        },
      });
    } else {
      // TODO: nee to change the i18n
      iziToast.show({
        message: me.getI18n('MSG.pleaseInputUserNameFirst'),
        color: 'yellow',
        icon: 'fas fa-exclamation-circle',
        iconColor: '#f1c40f',
        progressBarColor: '#f1c40f',
        timeout: 5000,
        resetOnHover: true,
        close: false,
        closeOnClick: true,
        transitionIn: 'fadeInDown',
        transitionOut: 'fadeOutUp',
        position: 'topCenter',
      });
    }
  },
  initComponent: function () {
    const me = this;
    document.title = `${me.getI18n('APP_NAME')} - ${me.getI18n('LOGIN.login')}`;
    Ext.applyIf(me, {
      items: [
        {
          // bind: {
          //   title: '{i18n.LOGIN.login}',
          // },
          xtype: 'form',
          frame: true,
          width: 900,
          bodyPadding: 10,
          title: `<p style=font-size:28px>${me.getI18n('LOGIN.login')}</p>`,
          defaultType: 'textfield',
          style: {
            'border-radius': '5px',
            'box-shadow': '0 4px 8px 0 rgba(0,0,0,0.2)',
          },
          itemId: 'title',
          defaults: {
            padding: '30 5 30 5',
            anchor: '100%',
            labelWidth: 180,
          },
          items: [
            {
              bind: {
                // fieldLabel: '{i18n.LOGIN.username}',
                emptyText: '{i18n.LOGIN.username}',
              },
              name: 'username',
              labelSeparator: '',
              allowBlank: false,
              fieldLabel: `<p style=font-size:28px>${me.getI18n('LOGIN.username')}:</p>`,
              itemId: 'username',
              listeners: {
                afterrender: function (field) {
                  this.setFieldStyle({ 'font-size': '36px' });
                  field.focus();
                },
                specialkey: function (field, e) {
                  if (e.getKey() == e.ENTER) me.login();
                },
              },
            },
            {
              bind: {
                // fieldLabel: '{i18n.LOGIN.pw}',
                emptyText: '{i18n.LOGIN.pw}',
              },
              name: 'password',
              labelSeparator: '',
              itemId: 'password',
              fieldLabel: `<p style=font-size:28px>${me.getI18n('LOGIN.pw')}:</p>`,
              allowBlank: false,
              inputType: 'password',
              listeners: {
                afterrender: function () {
                  this.setFieldStyle({ 'font-size': '36px' });
                },
                specialkey: function (field, e) {
                  if (e.getKey() == e.ENTER) me.login();
                },
              },
            },
            {
              xtype: 'combobox',
              width: 90,
              forceSelection: true,
              queryMode: 'local',
              displayField: 'icon',
              valueField: 'value',
              // bind: {
              // fieldLabel: '{i18n.LOGIN.locale}',
              // },
              itemId: 'locale',
              fieldLabel: `<p style=font-size:28px>${me.getI18n('LOGIN.locale')}:</p>`,
              labelSeparator: '',
              value: me.params.locale,
              store: {
                fields: ['icon', 'name', 'value', 'language', 'country'],
                data: locales,
              },
              style: {
                'margin-top': '20px',
              },
              listConfig: {
                getInnerTpl: function (displayField) {
                  return '<div style="font-size:24px">{name}</div>';
                },
              },
              listeners: {
                afterrender: function () {
                  this.setFieldStyle({ 'font-size': '36px' });
                },
                select: function (combo, record) {
                  me.changeLocale(record.get('language'), record.get('country'), record.get('value'));
                },
              },
            },
          ],

          buttons: [
            {
              // bind: {
              //   text: '{i18n.LOGIN.forgetPassword}',
              // },
              text: `<p style=font-size:24px>${me.getI18n('LOGIN.forgotPassword')}</p>`,
              itemId: 'btn1',
              minWidth: 180,
              formBind: false,
              handler: me.forgetPassword,
              scope: me,
            },
            '->',
            {
              // bind: {
              //   text: '{i18n.LOGIN.login}',
              // },
              text: `<p style=font-size:24px>${me.getI18n('LOGIN.login')}</p>`,
              itemId: 'btn2',
              width: 180,
              formBind: true,
              handler: me.login,
              scope: me,
            },
          ],
        },
      ],
    });
    me.callParent();
  },
});

const render = (locale, i18n) => {
  Ext.create('LoginPanel', {
    renderTo: Ext.getBody(),
    viewModel: {
      data: { i18n },
    },
    params: { locale },
  });
};

Ext.onReady(function () {
  const locale = Ext.util.Cookies.get(localeCookieName) || defaultLocale;
  loadI18n(locale, function (i18n) {
    if (!i18n) {
      loadI18n(defaultLocale, (i18n) => render(locale, i18n));
    } else {
      render(locale, i18n);
    }
  });
});
