<template>
  <BlockAdmin class="admin-registrations-page">
    <transition name="fadeIn" mode="out-in">
      <loader-ui
        v-if="
          (!currentUser && isAlive($route, ['query', 'user'])) ||
            (currentUser && !isAlive($route, ['query', 'user']))
        "
      />

      <div v-else-if="currentUser || isAlive($route, ['query', 'user'])">
        <div class="back-to-list" @click="backToList">
          <IconText icon="arrow-link-back">
            {{ $_tr('backToList') }}
          </IconText>
        </div>

        <registration-validation-admin
          v-if="currentUser"
          :uuid="$route.query.user"
          :user="currentUser"
          @onRegistrationUpdateSuccess="backToList"
        />
      </div>

      <div v-else class="registrations-listing">
        <table-listing
          id="registrations"
          endpoint="content/users"
          :fields="fields"
          :filters="filters"
          :items-per-page="50"
          :on-row-click="onClick"
          :interaction-disabled="disableRow"
          :headers="headers"
          :rows="rows"
        />
      </div>
    </transition>
  </BlockAdmin>
</template>

<script>
import { IconText } from 'inside-collection/atoms'

import RegistrationValidationAdmin from './RegistrationValidationAdmin'

import BlockAdmin from '@inside-administration/components/lib/BlockAdmin'

import { http } from '@inside-library/helpers/Http'

export default {
  name: 'AdminRegistrationPage',
  $_i18nRootPath: 'customs.ADMINISTRATION.REGISTRATIONS',
  components: {
    IconText,
    RegistrationValidationAdmin,
    BlockAdmin
  },
  data() {
    return {
      currentUser: null
    }
  },
  computed: {
    headers() {
      return [
        {
          value: this.$_tr('cols.fullname'),
          key: 'fullname'
        },
        {
          value: this.$_tr('cols.email'),
          sortable: true,
          key: 'email'
        },
        {
          value: this.$_tr('cols.created_at'),
          sortable: true,
          key: 'created_at',
          default: true,
          order: 'desc'
        },
        {
          value: this.$_tr('cols.updated_at'),
          sortable: true,
          key: 'updated_at'
        },
        {
          value: this.$_tr('cols.status')
        }
      ]
    },
    fields() {
      return [
        'firstname',
        'lastname',
        'name',
        'email',
        'registration_status',
        'created_at',
        'updated_at',
        {
          functions: ['title']
        },
        'company',
        'uuid'
      ]
    },
    filters() {
      return {
        is_from_ldap: 0
      }
    },
    beforeRouteUpdate(to, from, next) {
      if (!this.isAlive(to.$route, ['query', 'user'])) {
        this.currentUser = null
      }

      next()
      return null
    }
  },
  mounted() {
    // fetch currentUser
    if (!this.currentUser && this.isAlive(this.$route, ['query', 'user'])) {
      this.fetchUser()
    }
  },
  methods: {
    async fetchUser() {
      try {
        const params = {
          fields: this.fields,
          filters: {
            uuid: this.$route.query.user
          }
        }

        const { data } = await http.get('content/users', params)

        this.currentUser = data[0] || null

        if (
          !this.currentUser ||
          this.currentUser.registration_status !== 'pending'
        ) {
          this.backToList()
        }
      } catch (err) {
        throw new Error(err)
      }
    },
    backToList() {
      this.currentUser = null

      this.$router.replace({
        path: this.$route.path
      })
    },
    onClick(user) {
      if (user.registration_status === 'pending') {
        this.$router.replace({
          path: this.$route.path,
          query: { user: user.uuid }
        })

        this.currentUser = user
      }
    },
    disableRow(user) {
      return user.registration_status !== 'pending'
    },
    rows(fields) {
      return [
        {
          id: 'fullname',
          class: 'fullname',
          tag: 'p',
          value: this.$_username({
            firstname: fields.firstname,
            lastname: fields.lastname
          })
        },
        {
          id: 'email',
          tag: 'a',
          value: fields.email,
          data: {
            href: `mailto:${fields.email}`
          }
        },
        {
          id: 'created_at',
          tag: 'p',
          value: `${this.$_formatDate(fields.created_at)} ${this.$_formatDate(
            fields.created_at,
            'LTS'
          )}`
        },
        {
          id: 'updated_at',
          tag: 'p',
          value: this.$_formatDate(fields.updated_at)
        },
        {
          id: 'status',
          tag: 'p',
          class: `registration-status registration-status--${fields.registration_status}`,
          value: fields.registration_status
            ? this.$_tr(`registrationStatus.${fields.registration_status}`)
            : '-'
        }
      ]
    }
  }
}
</script>

<style lang="scss">
.admin-registrations-page {
  position: relative;
  z-index: 1;
  width: 100%;
  margin: 0 auto;

  .back-to-list {
    width: 100%;
    padding: 20px;
    margin: 0 auto 24px;
    background: var(--color-grey-200);
    cursor: pointer;

    .icon-text-ui .icon-ui {
      display: block;
      transform: scaleX(-1);
    }
  }

  p.registration-status {
    &--accepted {
      color: var(--color-valid);
    }
    &--pending {
      color: var(--color-warn);
    }
    &--declined {
      color: var(--color-invalid);
    }
  }
}
</style>
