<template>
  <b-navbar class="dashboard-header d-print-none p-0">
    <b-navbar-nav class="mr-auto flex-row">
      <b-nav-item class="toggler-link">
        <!-- left alligned menu items -->
        <b-btn @click="toggleMenu" class="toggler" variant="reset" data-qa="contentHeader-menuHamburger">
          <icon name="dashboard-hamburger" />
        </b-btn>
      </b-nav-item>
      <b-nav-item class="p-3 cv-info nav-item cv-info d-flex justify-content-center">
        <span class="no-wrap small">
          <span>{{ getActivePayCycleName }}</span>
          <span v-if="!$appSettings.evo.enable" class="pl-1">({{ getCurrentDate() }})</span>
        </span>
        <strong class="ml-3 text-primary small">
          BETA
        </strong>
      </b-nav-item>
    </b-navbar-nav>
    <b-navbar-nav class="flex-row align-items-center">
      <b-nav-item-dropdown
        class="fc-widget-effected pr-2"
        toggle-class="nav-link-custom"
        :text="getSelectedLanguageName"
        data-qa="contentHeader-language-dropdown"
      >
        <b-dropdown-item
          :key="index"
          :to="generatePath(language)"
          v-for="(language, index) in getAllLanguages"
          :data-qa="`contentHeader-${$helpers.kebabCase(language.text)}-language-dropdown-item`"
        >
          {{ language.text }}
        </b-dropdown-item>
      </b-nav-item-dropdown>
      <!-- right alligned menu items -->

      <b-nav-item class="pr-1">
        <b-button
          size="sm"
          @click="openFreshWidget"
          variant="outline-light-extra"
          class="rounded-circle px-1 border-0"
          data-qa="contentHeader-freshWidget-btn"
        >
          <icon name="dashboard-fwidget" class="icon-size-3 text-primary" />
        </b-button>
      </b-nav-item>

      <b-nav-item class="pr-1">
        <b-button
          size="sm"
          @click="openFAQ"
          variant="outline-light-extra"
          data-qa="contentHeader-faq-btn"
          :title="$t('Eshop.BottomMenu.FAQ')"
          class="rounded-circle px-1 border-0"
        >
          <icon name="question-circle" class="icon-size-3 text-primary" />
        </b-button>
      </b-nav-item>

      <div class="pr-1">
        <!--  Mobile version notification center navigation button-->
        <b-nav-item v-if="isMobileDevice">
          <b-button
            size="sm"
            @click="openNotification"
            variant="outline-light-extra"
            data-qa="contentHeader-notification-btn"
            class="rounded-circle px-1 border-0 notification"
          >
            <icon name="dashboard-notification" class="icon-size-3 text-primary" />
            <b-badge variant="danger" v-show="getNotificationTotal">{{ getNotificationTotal }}</b-badge>
          </b-button>
        </b-nav-item>

        <!-- Desktop version notification center navigation button-->
        <b-nav-item-dropdown v-else right no-caret menu-class="pt-3 pb-0" ref="notification-dropdown">
          <template v-slot:button-content>
            <b-button
              size="sm"
              variant="outline-light-extra"
              @click="loadNotification"
              data-qa="contentHeader-notification-btn"
              class="rounded-circle px-1 border-0 notification"
            >
              <icon name="dashboard-notification" class="icon-size-3 text-primary" />
              <b-badge variant="danger" v-show="getNotificationTotal">
                {{ getNotificationTotal }}
              </b-badge>
            </b-button>
          </template>
          <div class="vw-75">
            <notification-center-dropdown
              is-overview-mode
              scope="header"
              data-qa-prefix="contentHeader"
              ref="headerNotificationCenter"
              :external-data-source="getNotificationList"
            />
          </div>
        </b-nav-item-dropdown>
      </div>

      <b-nav-item>
        <b-button
          size="sm"
          :to="logoutUrl"
          variant="outline-light-extra"
          data-qa="contentHeader-logout-btn"
          class="rounded-circle px-1 border-0"
        >
          <icon name="dashboard-logout" class="icon-size-3 text-primary" />
        </b-button>
      </b-nav-item>
    </b-navbar-nav>
    <notification-center-modal ref="notificationCenterModal" />
  </b-navbar>
</template>
<script>
import { LOGOUT_URL } from '@/config/defaults.js'
import { ESHOP_LANGUAGE as LANGUAGE_URL } from '@/config/url-prefix'
import { mapGetters, mapActions } from 'vuex'
import moment from 'moment'
import { mapMasterDataId } from '@/app/_global/mixins'
import NotificationCenterModal from '@/app/_global/components/blocks/NotificationCenterModal'
import NotificationCenterDropdown from '@/app/_global/components/elements/NotificationCenter'

export default {
  name: 'ContentHeader',
  components: { NotificationCenterModal, NotificationCenterDropdown },
  data() {
    return {
      logoutUrl: LOGOUT_URL,
      counter: false,
      refreshed: true,
      remainingTime: '',
      minutes: 15,
      timerSec: 60 - new Date().getSeconds(),
      timerMin: 15 - new Date().getMinutes(),
      interval: 1000,
      isMobileDevice: false,
      payCycleOptions: [],
      notificationData: [],
      notificationDataTotal: 0,
      payCycleFilter: { filter_type: 'current', sort: 'id', order: 'desc', limit: 2 },
    }
  },
  async mounted() {
    this.isMobileDevice = await this.isMobile()
    setInterval(this.countDown, this.interval)
    let currentAppSidebarMode = this.getLayoutMode('appSidebar', false)
    this.loadCwScheduleList(this.payCycleFilter).then(cycles => {
      this.payCycleOptions = (cycles || []).map(cycle => this.$t('Dashboard.Landing.Cw.Label', { date: cycle.cw_name }))
    })
    if (currentAppSidebarMode !== false) {
      let app = document.querySelector('#app')
      if (app !== null) {
        app.classList.add(currentAppSidebarMode)
      }
    }
    let currentSidebarMode = this.getLayoutMode('sidebar', false)
    if (currentSidebarMode !== false) {
      let sideBar = document.querySelector('#sidebar')
      if (sideBar !== null) {
        sideBar.parentElement.classList.add(currentSidebarMode)
      }
    }
    this.loadNotification()
    if (this.$echo) {
      this.$echo.channel(`notifications.user.${this.getMemberDetails.user_id}`).listen('.new-notifications', event => {
        this.notificationDataTotal = event.unread_count || 0
      })
    }
  },
  methods: {
    ...mapActions(['layoutBlocks', 'getEformLink', 'isMobile', 'loadUserNotifications', 'loadCwScheduleList']),
    overlapClicked() {
      this.toggleMenu()
    },
    toggleMenu: function(e) {
      if (document.querySelector('#sidebar').parentElement.classList.toggle('sidebar-toggle')) {
        this.layoutBlocks({ block: 'sidebar', layout: 'sidebar-toggle' })
      } else {
        this.layoutBlocks({ block: 'sidebar', layout: false })
      }
      if (document.querySelector('#app').classList.toggle('app-sidebar-toggle')) {
        this.layoutBlocks({ block: 'appSidebar', layout: 'app-sidebar-toggle' })
      } else {
        this.layoutBlocks({ block: 'appSidebar', layout: false })
      }
      // For mobile toggles
      document.querySelector('#app').classList.toggle('app-sidebar-open')
      let freshwidget = document.querySelector('.freshwidget-button')
      if (freshwidget !== null) {
        freshwidget.classList.toggle('freshwidget-button-toggle')
      }
      let lcChatLayout = document.querySelector('#lc_chat_layout')
      if (lcChatLayout !== null) {
        lcChatLayout.classList.toggle('lc_chat_layout-button-toggle')
      }
    },
    getCurrentDate() {
      return moment(new Date()).format('DD/MM/YYYY')
    },
    generatePath(language) {
      return LANGUAGE_URL + '/' + language.value
    },
    countDown() {
      var n = this.timerSec
      if (this.timerMin < this.minutes + 1) {
        if (!this.counter) {
          if (this.timerMin > 0) {
            this.counter = true
            this.refreshed = false
          }
        } else if (n > 0) {
          n = n - 1
          this.timerSec = n
          this.remainingTime = '00:' + this.timerMin.toString().padStart(2, '0') + ':' + n.toString().padStart(2, '0')
        } else if (n === 0) {
          if (this.timerMin > 0) {
            this.timerSec = 60
            this.timerMin = this.timerMin - 1
          } else {
            clearInterval(this.interval)
            this.counter = false
            this.remainingTime = ''
          }
        } else {
          clearInterval(this.interval)
          this.counter = false
          this.remainingTime = ''
        }
      }
    },
    refreshCurrentPage() {
      this.refreshed = true
      window.location.reload()
    },
    openFreshWidget() {
      let freshwidget = document.querySelector('#freshwidget-button a')

      if (freshwidget !== null) {
        freshwidget.click()
      }
    },
    openFAQ() {
      this.resolveMasters.then(() => {
        this.getEformLink([this.faqId]).then(() => {
          if (this.getEformLinkData !== undefined) {
            window.open(this.getEformLinkData.link, '_blank')
          }
        })
      })
    },
    async openNotification() {
      this.notificationDataTotal = 0
      this.$refs['notificationCenterModal'].show()
    },
    async loadNotification(event) {
      this.notificationDataTotal = 0
      if (this.$refs['notification-dropdown'] && !this.$refs['notification-dropdown'].visible) {
        await this.loadUserNotifications({ limit: 0, has_read: false }).then(data => {
          this.notificationData = data || []
          if (this.notificationData.length && !event) {
            this.notificationDataTotal = this.notificationData.length
          }
        })
      }
    },
  },
  computed: {
    ...mapGetters([
      'getAppStatus',
      'getLayoutMode',
      'getMemberDetails',
      'getSelectedCountry',
      'getAllLanguages',
      'getSelectedLanguageName',
      'getEformLinkData',
    ]),
    ...mapMasterDataId({
      SMART_LIBRARY_EFORM_FILE_TYPE: {
        faqId: 'FAQ',
      },
    }),
    showBonusCalculationMessage() {
      return new Date().getMinutes() < this.minutes + 3
    },
    getNotificationList() {
      return this.notificationData
    },
    getNotificationTotal() {
      return (this.notificationDataTotal > 99 && '99+') || this.notificationDataTotal
    },
    getActivePayCycleName() {
      return this.payCycleOptions.join(' / ')
    },
  },
  beforeDestroy() {
    // remove toggle state on layout change
    let freshwidget = document.querySelector('.freshwidget-button')
    if (freshwidget) {
      freshwidget.classList.remove('freshwidget-button-toggle')
    }
    let app = document.querySelector('#app')
    if (app) {
      app.classList.remove('app-sidebar-toggle')
      app.classList.remove('sidebar-toggle')
    }
    let sidebar = document.querySelector('#sidebar')
    if (sidebar) {
      sidebar.parentElement.classList.remove('sidebar-toggle')
    }
  },
  destroyed() {
    if (this.$echo) {
      this.$echo.leave(`notifications.user.${this.getMemberDetails.user_id}`)
    }
  },
}
</script>
