<template>
  <div class="user">
    <div v-if="user">
      <h2 class="title is-2">{{ user.userId }}</h2>
      <div class="columns is-centered">
        <div class="column">
          <lang-changer />
        </div>
        <div class="column">
          <div class="buttons is-centered">
            <button class="button is-warning" type="button" @click="logout" v-t="'user.logout'"></button>
            <button class="button is-warning" type="button" @click="purge" v-t="'user.purge'"></button>
            <confirm-button class="is-danger" @confirm="remove">{{ $t('user.delete') }}</confirm-button>
          </div>
        </div>
      </div>
      <hr />
      <account-list />
      <div>
        <h3 class="subtitle is-3">Comptes cloturés</h3>
        <account-list :archived="true" />
      </div>
    </div>
    <div v-else>
      <div class="tabs is-centered is-fullwidth">
        <ul>
          <li :class="{ 'is-active': activeTab === 'login'}">
            <a href="#" @click.prevent="activeTab = 'login'" v-t="'user.login'"></a>
          </li>
          <li :class="{ 'is-active': activeTab === 'signup'}">
            <a href="#" @click.prevent="activeTab = 'signup'" v-t="'user.signup'"></a>
          </li>
        </ul>
      </div>
      <div class="user-container">
        <div v-show="activeTab === 'login'">
          <div class="field is-horizontal">
            <div class="field-label is-normal">
              <label class="label">Pseudo</label>
            </div>
            <div class="field-body">
              <div class="field">
                <p class="control">
                  <input
                    name="login"
                    id="login"
                    class="input"
                    type="text"
                    @keyup.enter="signin"
                    v-model.trim="userId"
                  />
                </p>
              </div>
            </div>
          </div>
          <div class="field is-horizontal">
            <div class="field-label is-normal">
              <label class="label" v-t="'user.password'"></label>
            </div>
            <div class="field-body">
              <div class="field">
                <p class="control">
                  <input
                    name="password"
                    id="password"
                    class="input"
                    type="password"
                    @keyup.enter="signin"
                    v-model="password"
                  />
                </p>
              </div>
            </div>
          </div>
          <button
            class="button is-primary"
            :class="{ 'is-loading': isLoading }"
            @click="signin"
            v-t="'user.login'"
          ></button>
        </div>
        <div v-show="activeTab === 'signup'">
          <div class="columns is-centered">
            <div class="column is-half">
              <div class="field is-horizontal">
                <div class="field-label is-normal">
                  <label class="label">pseudo</label>
                </div>
                <div class="field-body">
                  <div class="field">
                    <p class="control">
                      <input
                        required
                        class="input"
                        type="text"
                        @keyup.enter="register"
                        v-model.trim="userId"
                      />
                    </p>
                  </div>
                </div>
              </div>
              <!-- <div class="field is-horizontal">
                <div class="field-label is-normal">
                  <label class="label">email</label>
                </div>
                <div class="field-body">
                  <div class="field">
                    <p class="control">
                      <input
                        required
                        class="input"
                        type="email"
                        @keyup.enter="register"
                        v-model.trim="email"
                      >
                    </p>
                  </div>
                </div>
              </div>-->
              <div class="field is-horizontal">
                <div class="field-label is-normal">
                  <label class="label" v-t="'user.password'"></label>
                </div>
                <div class="field-body">
                  <div class="field">
                    <p class="control">
                      <input
                        required
                        class="input"
                        type="password"
                        @keyup.enter="register"
                        v-model="password"
                      />
                    </p>
                  </div>
                </div>
              </div>
              <div class="field is-horizontal">
                <div class="field-label is-normal">
                  <label class="label" v-t="'user.confirm_password'"></label>
                </div>
                <div class="field-body">
                  <div class="field">
                    <p class="control">
                      <input
                        required
                        class="input"
                        type="password"
                        @keyup.enter="register"
                        v-model="confirmPassword"
                      />
                    </p>
                  </div>
                </div>
              </div>
              <div class="field is-horizontal">
                <div class="field-label is-normal">
                  <label class="label" v-t="'user.firstname'"></label>
                </div>
                <div class="field-body">
                  <div class="field">
                    <p class="control">
                      <input
                        class="input"
                        type="text"
                        @keyup.enter="register"
                        v-model.trim="firstname"
                      />
                    </p>
                  </div>
                </div>
              </div>
              <div class="field is-horizontal">
                <div class="field-label is-normal">
                  <label class="label" v-t="'user.lastname'">nom</label>
                </div>
                <div class="field-body">
                  <div class="field">
                    <p class="control">
                      <input
                        class="input"
                        type="text"
                        @keyup.enter="register"
                        v-model.trim="lastname"
                      />
                    </p>
                  </div>
                </div>
              </div>
              <!-- <pricing-table first-plan="free" @choose="plan => user.premium = plan === 'premium'"/> -->
              <hr />
              <button
                class="button is-primary"
                :class="{ 'is-loading': isLoading }"
                @click="register(false)"
                v-t="'user.signup'"
              ></button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="modal" :class="{ 'is-active': show }">
      <div class="modal-background"></div>
      <div class="modal-card">
        <section
          class="modal-card-body"
        >Voulez-vous récupérer les comptes utilisés avant d'être inscrit ?</section>
        <footer class="modal-card-foot">
          <button type="button" class="button is-success" @click="toReplicate(true)">Oui</button>
          <button type="button" class="button" @click="toReplicate(false)">Non</button>
        </footer>
      </div>
      <button class="modal-close is-large" aria-label="close"></button>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
import { Action, Getter } from 'vuex-class'
import { slug } from '@/utils'
import notif from '@/utils/notif'
import IUser from '@/models/IUser'
import LangChanger from '@/components/LangChanger.vue'
import userService from '@/services/UserService'

const enableAnonymous: boolean = false

@Component({
  components: {
    LangChanger,
    'account-list': () => import('@/components/AccountList.vue'),
    'confirm-button': () => import('@/components/ConfirmButton.vue'),
    'pricing-table': () => import('@/components/PricingTable.vue')
  }
})
export default class User extends Vue {
  @Prop({ type: String, required: false, default: '' })
  public premail!: string
  @Getter
  public user!: IUser | null
  @Action
  public login!: any
  @Action
  public signup!: any
  @Action
  public logout!: any
  @Action
  public remove!: any
  public activeTab: string = 'login'
  public userId: string = ''
  public email: string = ''
  public password: string = ''
  public confirmPassword: string = ''
  public firstname: string = ''
  public lastname: string = ''
  public isLoading: boolean = false
  public show: boolean = false
  public replicate: boolean = false
  public confirmed: boolean = false

  public mounted(): void {
    if (this.premail) {
      this.email = this.premail
    }
  }

  public async signin(): Promise<void> {
    this.isLoading = true
    await this.login({
      userId: this.userId,
      password: this.password
    })
    this.isLoading = false
  }

  public toReplicate(replicate: boolean): void {
    this.replicate = replicate
    this.show = false
    this.register(true)
  }

  public async register(confirmed: boolean): Promise<void> {
    if (!this.validateRegistration()) {
      return
    }
    try {
      if (
        enableAnonymous &&
        (await userService.hasAnonymousData()) &&
        !confirmed
      ) {
        if (!this.show) {
          this.show = true
        }
        return
      }
    } catch (error) {
      notif.error(
        `Une erreur est survenue à la vérification d'un compte anonyme déjà créé.`
      )
      // tslint:disable-next-line
      console.warn({ error })
    }
    this.isLoading = true
    try {
      const user: IUser = {
        userId: this.userId,
        email: this.email,
        premium: false,
        slugEmail: this.slugEmail,
        firstname: this.firstname,
        lastname: this.lastname
      }
      await this.signup({
        user,
        password: this.password,
        replicate: this.replicate
      })
    } catch (error) {
      notif.error(
        `Une erreur est survenue à la création du compte utilisateur.`
      )
      // tslint:disable-next-line
      console.warn({ error })
    }
    this.isLoading = false
  }

  public validateRegistration(): boolean {
    if (!this.userId) {
      notif.error('Un pseudo est obligatoire.')
      return false
    }
    if (this.password !== this.confirmPassword) {
      notif.error('Les mots de passe doivent être identique.')
      return false
    }
    return true
  }

  public async purge(): Promise<void> {
    await userService.purge()
    notif.success(this.$t('user.purgeDone').toString())
  }

  public get slugEmail(): string {
    return slug(this.email)
  }
}
</script>

<style scoped>
.user {
  padding: 15px 0;
}
</style>
