<template>
  <transition
    appear
    enter-active-class="animated fadeIn"
    leave-active-class="animated fadeOut"
  >
    <div @click.stop class="managers-form shadow-2">
      <div class="flex items-start no-wrap bg-background">
        <selected-managers
          @unsubscribe-manager="unselectManagers([$event])"
          :managers="selectedManagers"
        >
          <subscribe-btn
            v-if="!currentManagerIsSelected || isShowAddMeBtn"
            @click="selectCurrentManager"
            :label="labelAddMe"
          />
        </selected-managers>
        <div class="q-pa-sm q-ml-auto">
          <ui-btn-close @click="close" />
        </div>
      </div>

      <div class="q-px-lg q-pt-lg">
        <q-input
          v-model="searchQuery"
          :debounce="300"
          label="Имя сотрудника..."
          autofocus
        />
      </div>
      <div v-if="searchQuery" class="q-px-sm q-py-lg">
        <search-result
          @subscribe-managers="selectManagers"
          :managers="foundManagers"
        />
      </div>
      <div v-else class="q-px-sm q-py-lg">
        <managers-groups
          @subscribe-managers="selectManagers"
          @unsubscribe-managers="unselectManagers"
          :managers-by-group="managersByGroup"
          :manager-uids="uids"
          :label-empty="labelEmptyGroup"
        />
      </div>
    </div>
  </transition>
</template>

<style scoped lang="sass">
.managers-form
  position: absolute
  z-index: 10
  top: 0
  left: 0
  right: 0
  border-radius: 16px
  overflow: hidden
  background-color: #fff
</style>

<script lang="ts">
import { Component, Emit, Prop, Vue } from 'vue-property-decorator'
import { getQueryVariants } from '@/widgets/messages/helpers/search.helper'
import { Manager, ManagerCollectionsByGroup } from '@/types/Manager'
import SelectedManagers from '@/widgets/base/components/managers-select/SelectedManagers.vue'
import SearchResult from '@/widgets/base/components/managers-select/SearchResult.vue'
import ManagersGroups from '@/widgets/base/components/managers-select/ManagersGroups.vue'
import SubscribeBtn from '@/widgets/base/components/managers-select/SubscribeBtn.vue'
import UiBtnClose from '@/lib-components/buttons/UiBtnClose.vue'
import { QInput } from 'quasar'

@Component({
  components: {
    SelectedManagers,
    SearchResult,
    ManagersGroups,
    SubscribeBtn,
    UiBtnClose,
    QInput,
  },
})
export default class ManagersSelect extends Vue {
  @Prop({ type: Array, required: true })
  uids!: string[]

  @Prop({ type: Array, required: true })
  managers!: Manager[]

  @Prop({ type: Object, required: true })
  currentManager!: Manager

  @Prop({ type: Object, required: true })
  managersByGroup!: ManagerCollectionsByGroup

  @Prop({ type: String, required: true })
  labelAddMe!: string

  @Prop({ type: String, required: true })
  labelEmptyGroup!: string

  @Prop({ type: Boolean })
  isShowAddMeBtn?: boolean

  searchQuery = ''

  get isShowSubscribeBtn() {
    if (this.isShowAddMeBtn) {
      return true
    }

    return !this.currentManagerIsSelected && this.isShowAddMeBtn !== false
  }

  get foundManagers(): Manager[] {
    if (!this.searchQuery) {
      return []
    }

    const queryVariants: string[] = getQueryVariants(this.searchQuery)

    return this.managers.filter(manager => {
      return (
        manager.enabled &&
        !this.selectedManagers.includes(manager) &&
        queryVariants.some(
          queryVariant =>
            manager.firstName.toLowerCase().includes(queryVariant) ||
            manager.lastName.toLowerCase().includes(queryVariant)
        )
      )
    })
  }

  get selectedManagers(): Manager[] {
    return this.managers.filter(manager => this.uids.includes(manager.id))
  }

  get currentManagerIsSelected(): boolean {
    return this.uids.includes(this.currentManager.id)
  }

  selectManagers(managers: Manager[]) {
    const idsSet = new Set([
      ...this.uids,
      ...managers.map(manager => manager.id),
    ])

    this.input(Array.from(idsSet))
  }

  unselectManagers(managers: Manager[]) {
    const subscribedIds = [...this.uids]
    const managersIds = managers.map(manager => manager.id)

    managersIds.forEach(id => {
      const index = subscribedIds.indexOf(id)

      if (index !== -1) {
        subscribedIds.splice(index, 1)
      }
    })

    this.input(subscribedIds)
  }

  closeOnGlobalClick() {
    this.close()
  }

  mounted() {
    setTimeout(() => {
      document.addEventListener('click', this.closeOnGlobalClick)
    }, 300)
  }

  destroyed() {
    document.removeEventListener('click', this.closeOnGlobalClick)
  }

  @Emit()
  input(ids: string[]) {
    return ids
  }

  @Emit()
  selectCurrentManager() {
    return true
  }

  @Emit()
  close() {
    return true
  }
}
</script>
