<template>
  <div class="notification-center-panel">
    <div class="px-3">
      <b-row>
        <b-col>
          <h2 class="m-0 text-black">{{ $t('Notification.Title') }}</h2>
        </b-col>
        <b-col cols="auto">
          <b-button v-if="getNotificationData.length > 0" class="px-0" variant="link" @click="readNotifications(true)">
            {{ $t('Notification.Button.MarkAllAsRead.Label') }}
          </b-button>
        </b-col>
      </b-row>
    </div>
    <hr class="mb-0" />
    <b-alert variant="chart-color-two" :show="isLoading('readNotification')" class="rounded-0 border-0">
      <b-spinner small class="mb-1 mr-2" />
      <span>{{ $t('Common.Updating') }}</span>
    </b-alert>

    <b-overlay :show="isLoading('loadingNotification')" variant="white">
      <!-- Overlay loading block-->
      <template v-slot:overlay>
        <b-spinner class="mx-2 text-primary" />
        <strong class="h4">{{ $t('Common.Loading') }}</strong>
      </template>

      <div class="pb-3 pt-2 mx-1 custom-scroll-bar">
        <!-- Error or no data block-->
        <div v-if="getNotificationData.length < 1 || getErrors('loadNotification')" class="text-center mb-5">
          <icon name="dashboard-notification" class="my-4 text-light icon-size-5" />
          <h4>{{ $t('Notification.NoNotification.Title') }}</h4>
          <p>{{ $t('Notification.NoNotification.Description') }}</p>
          <b-button
            v-if="!this.isOverviewMode"
            variant="outline-primary"
            @click="loadNotifications(0)"
            :data-qa="`${dataQaPrefix}-notificationCenter-notificationRefresh-btn`"
          >
            <icon name="sync" class="mr-2" />
            <span>{{ $t('Common.Refresh') }}</span>
          </b-button>
        </div>

        <!-- Notification list-->
        <b-list-group
          v-else-if="scope !== 'popup' || !isLoading('loadingNotification')"
          class="notification-listing overflow-y-auto"
        >
          <b-list-group-item
            button
            :key="index"
            class="border-0 pb-0"
            v-for="(notification, index) in getNotificationData"
            @click="viewNotification(notification)"
          >
            <b-row>
              <b-col cols="auto" :id="`${scope}-notification-${notification.id}`" class="notification">
                <icon
                  class="icon-size-4"
                  name="dashboard-notification"
                  :class="notification.has_read ? 'text-light' : 'text-primary'"
                />
                <b-badge v-if="!notification.has_read" variant="danger" class="ml-3 badge-empty">
                  <span> </span>
                </b-badge>
              </b-col>

              <b-col>
                <b-row>
                  <b-col>
                    <div class="text-black font-weight-bold">
                      {{ notification.message || $t('Common.Error.Untitled') }}
                    </div>
                    <b-badge v-if="!isOverviewMode" variant="primary" class="font-size-7 font-weight-normal px-2">
                      {{ notification.type }}
                    </b-badge>
                    <div>
                      <small class="text-black-50 pt-1">{{ getRelativeTimeFormat(notification.created_at) }}</small>
                    </div>
                  </b-col>
                </b-row>
                <hr class="mb-0" />
              </b-col>
            </b-row>
          </b-list-group-item>
        </b-list-group>
      </div>

      <div>
        <b-button
          v-if="isOverviewMode"
          block
          size="lg"
          variant="primary"
          class="rounded-0 border-0"
          @click="openNotificationModal"
          :data-qa="`${dataQaPrefix}-notificationCenter-openNotificationModal-btn`"
        >
          {{ $t('Notification.ViewAllNotification.Label') }}
        </b-button>
        <div v-else-if="getNotificationTotal > 1" class="pb-1">
          <b-pagination
            pills
            align="center"
            v-model="currentPage"
            hide-goto-end-buttons
            :limit="paginatorOptionsLimit"
            :per-page="notificationPerPage"
            :total-rows="getNotificationTotal"
            :next-text="$t('Common.Paginator.Next')"
            :prev-text="$t('Common.Paginator.Previous.Short')"
          />
        </div>
      </div>
    </b-overlay>
  </div>
</template>

<script>
import _ from 'lodash'
import { mapGetters, mapActions } from 'vuex'
import moment from 'moment'

export default {
  name: 'NotificationCenter',
  props: {
    scope: { type: String, default: 'popup' },
    externalDataSource: { type: Array },
    dataQaPrefix: { type: String, required: true },
    isOverviewMode: { type: Boolean, default: false },
    notificationPerPage: { type: Number, default: 6 },
  },
  data() {
    return {
      currentPage: 1,
      paginatorOptionsLimit: 3,
    }
  },
  computed: {
    ...mapGetters(['getNotificationList', 'getNotificationTotal', 'getErrors', 'isLoading']),
    getNotificationData() {
      return this.externalDataSource || this.getNotificationList
    },
  },
  async mounted() {
    if (!(await this.isMobile())) {
      this.paginatorOptionsLimit = 5
    }
  },
  methods: {
    ...mapActions(['loadUserNotifications', 'isMobile', 'readUserNotification']),
    openNotificationModal() {
      this.$bvModal.show('notification_center_modal')
    },
    loadNotifications(page = 0) {
      if (page === 0 && this.currentPage !== 1) {
        // If user not in 1st page and offset is still default value; then navigate to 1st page.
        // This block mainly design for refresh button above
        this.currentPage = 1
      } else {
        let offset = this.notificationPerPage * page
        this.loadUserNotifications({ offset, limit: this.notificationPerPage })
      }
    },
    getRelativeTimeFormat(dateTime) {
      return moment(dateTime).fromNow()
    },
    readNotifications(markAll = true, ids = []) {
      let notificationList =
        (markAll && _.cloneDeep(this.getNotificationData.filter(data => !data.has_read))) || ids.map(id => ({ id }))

      notificationList.forEach(notification => {
        let notificationElement = document.getElementById(`${this.scope}-notification-${notification.id}`)
        notificationElement.querySelector('svg').classList.remove('text-primary')
        notificationElement.querySelector('svg').classList.add('text-light')
        notificationElement.querySelector('.badge').remove()
      })
      this.readUserNotification({ ids, mark_all: markAll })
    },
    viewNotification(notification) {
      if (!notification.has_read) {
        this.readNotifications(false, [notification.id])
      }
    },
  },
  watch: {
    currentPage: {
      handler(val) {
        if (!this.isOverviewMode) {
          this.loadNotifications(val - 1)
        }
      },
      immediate: true,
    },
  },
}
</script>
