<template>
  <div class="lg-login">
    <div
      v-if="!getIsAuthed"
      class="lg-login__panel"
    >
      <div
        v-if="!isUsePopup"
        class="lg-login__brand"
      >
        <img
          :src="configApp.logoDark"
          class="lg-login__logo"
          alt="AutoShopee"
        >
      </div>

      <div class="lg-login__card">
        <h2 class="lg-login__title">
          {{ $t('LOGIN_USER') }}
        </h2>

        <Form
          ref="loginForm"
          class="lg-login__form"
          :model="form"
          :rules="rules"
        >
          <FormItem prop="username">
            <Input
              v-model="form.username"
              :placeholder="$t('USERNAME')"
              prefix="ios-person"
              size="large"
              @keyup.enter.native="loginSubmit"
            />
          </FormItem>
          <FormItem prop="password">
            <Input
              v-model="form.password"
              type="password"
              :placeholder="$t('PASSWORD')"
              prefix="ios-lock"
              size="large"
              password
              @keyup.enter.native="loginSubmit"
            />
          </FormItem>
          <FormItem class="mb-0">
            <Button
              class="lg-login__submit"
              type="primary"
              long
              size="large"
              :loading="loading"
              @click="loginSubmit"
            >
              {{ $t('BTN_LOGIN') }}
            </Button>
          </FormItem>
        </Form>

        <div class="lg-login__divider">
          <span class="lg-login__divider-text">
            {{ $t('REGISTER_OR') }}
          </span>
        </div>

        <Button
          class="lg-login__alt"
          long
          size="large"
          @click="openPageRegister"
        >
          {{ $t('BTN_REGISTER') }}
        </Button>

        <p class="lg-login__note">
          {{ $t('LOGIN_PAGE_NOTE') }}
        </p>
      </div>
    </div>

    <Alert
      v-else
      class="lg-login__authed"
      type="success"
      show-icon
    >
      {{ $t('USER_WAS_LOGGED') }}
    </Alert>
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import delay from 'delay';
import { loggerVue } from '@/plugins/logger';

export default {
  name: 'LoginIndex',
  data() {
    return {
      loading: false,
      form: {
        username: '',
        password: '',
      },
      returnUrl: '',
    };
  },
  computed: {
    rules() {
      return {
        username: [
          { required: true, message: this.$t('VALIDATE_FIELD_REQUIRED'), trigger: 'blur' },
        ],
        password: [
          { required: true, message: this.$t('VALIDATE_FIELD_REQUIRED'), trigger: 'blur' },
          { min: 6, message: this.$t('VALIDATE_PASSWORD_MIN'), trigger: 'blur' },
        ],
      };
    },
  },
  methods: {
    ...mapActions(['SetToken', 'SetUser', 'SetLogin', 'Logout']),
    openPageRegister() {
      this.RouterPath('/register');
    },
    async loginSubmit() {
      const valid = await new Promise((resolve) => {
        this.$refs.loginForm.validate((result) => resolve(result));
      });

      if (!valid) {
        return;
      }

      this.loading = true;

      try {
        const result = await this.UserLogin(this.form);

        if (!(result.success && result.token)) {
          this.$Message.error(result.msg || this.$t('LOGIN_ERROR'));

          throw {
            msg: 'LOGIN_ERROR',
            result,
          };
        }

        this.$Message.success(this.$t('LOGIN_SUCCESS'));

        await delay(500);

        if (this.returnUrl) {
          return this.RouterPath(this.returnUrl);
        }

        this.RouterTo('root');
      } catch (error) {
        loggerVue.error({
          msg: 'LOGIN_ERROR',
          error,
        });
      }

      this.loading = false;
    },
    autoLogin() {
      const { username, password, ref } = this.$route.query;

      if (!(username && password)) {
        return false;
      }

      this.form.username = username;
      this.form.password = password;

      if (ref === 'shop-manager') {
        this.SetUseShopManager(true);
      }

      delete this.$route.params.username;
      delete this.$route.params.password;

      this.$router.replace({
        name: this.$route.name,
        params: this.$route.params,
        query: {},
      });

      const loginMethod = this.loginSubmit;
      return setTimeout(loginMethod, 200);
    },
  },
  created() {
    this.returnUrl = this.$route.query.returnUrl;
    this.form.username = this.getUsername;
    this.form.password = this.getPassword;
    this.autoLogin();
  },
};
</script>

<style lang="scss" scoped>
@import '@/vue/styles/tokens.scss';

.lg-login {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 16px 0;

  &__panel {
    width: 100%;
    max-width: 380px;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  &__brand {
    display: flex;
    justify-content: center;
  }

  &__logo {
    height: 36px;
    object-fit: contain;
  }

  &__card {
    @include card(20px);

    border: 1px solid $c-border;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  &__title {
    margin: 0;
    text-align: center;
    font-size: 18px;
    font-weight: 700;
    color: $c-text-strong;
  }

  &__form {
    display: block;

    .ivu-form-item {
      margin-bottom: 16px;
    }

    .ivu-form-item.mb-0 {
      margin-bottom: 0;
    }

    .ivu-input {
      border-radius: $radius-item;
      border-color: $c-border-input;
      color: $c-text-strong;
      transition: border-color $motion-fast, box-shadow $motion-fast;

      &::placeholder {
        color: $c-text-placeholder;
      }

      &:hover {
        border-color: $c-brand-hover;
      }

      &:focus {
        border-color: $c-brand;
        box-shadow: 0 0 0 2px $c-brand-tint;
      }
    }

    .ivu-input-prefix i {
      color: $c-text-muted;
    }
  }

  &__submit.ivu-btn {
    border-radius: $radius-item;
    font-weight: 600;
    background: $c-brand;
    border-color: $c-brand;
    box-shadow: none;
    transition: background $motion-fast, border-color $motion-fast;

    &:hover,
    &:focus {
      background: $c-brand-hover;
      border-color: $c-brand-hover;
    }

    &:active {
      background: $c-brand-active;
      border-color: $c-brand-active;
    }
  }

  &__divider {
    display: flex;
    align-items: center;
    gap: 12px;
    color: $c-text-muted;
    font-size: 12px;

    &::before,
    &::after {
      content: '';
      flex: 1;
      height: 1px;
      background: $c-border;
    }
  }

  &__divider-text {
    white-space: nowrap;
  }

  &__alt.ivu-btn {
    border-radius: $radius-item;
    font-weight: 600;
    color: $c-brand;
    border-color: $c-border-input;
    background: $c-surface;
    transition: color $motion-fast, border-color $motion-fast, background $motion-fast;

    &:hover,
    &:focus {
      color: $c-brand-hover;
      border-color: $c-brand-hover;
      background: $c-brand-tint;
    }
  }

  &__note {
    margin: 0;
    text-align: center;
    font-size: 12px;
    line-height: 1.5;
    color: $c-text-placeholder;
  }

  &__authed {
    margin-top: 10px;
  }
}
</style>
