<template>
  <div :class="`${dropdownPosition} user-filter`">
    <slot>
      <button :class="`btn btn-${type} dropdown-toggle`" type="button" data-toggle="dropdown" aria-expanded="false" :disabled="disabled">
        <i class="mdi mdi-account-multiple-outline" />
        {{ caption }}
      </button>
    </slot>
    <div class="dropdown-menu p-2">
      <input v-model="searchQuery" type="email" class="form-control" :placeholder="searchPlaceholder">

      <div class="user-container" :style="{maxHeight: customStyle.containerHeight}">
        <div 
          v-for="item in filteredList" 
          :key="`user-${item.payload.email}`" 
          class="user-entry rounded d-flex align-items-center justify-content-start p-1 mt-2"
          @click.stop="toggleSelection(item)"
        >
        <slot name="item" :item="item">
          <div class="mr-2">
            <input v-model="item.selected" type="checkbox" :disabled="isMaxSelectionReached && !item.selected">
          </div>
          <div class="mr-2">
            <img v-if="item.payload.image" :src="item.payload.image" class="rounded-circle" :style="{height: customStyle.imageHeight, width: customStyle.imageHeight}">
            <div v-else class="user-placeholder d-flex align-items-center justify-content-center">
              <i class="bi bi-person" />
            </div>
          </div>
          <div>
            <h2 :style="{'font-size': customStyle.nameFontSize}">{{ item.payload.name }}</h2>
            <p :style="{'font-size': customStyle.emailFontSize}">{{ item.payload.email }}</p>
          </div>
        </slot>
        </div>
      </div>

      <button class="btn btn-sm btn-secondary mt-2 w-100" type="button" @click="selectUsers">
        {{ caption }}
        <span v-show="selectedCount">({{ selectedCount }})</span>
      </button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    caption: {
      type: String,
      default() { return 'Assign' }
    },
    searchPlaceholder: {
      type: String,
      default() { return 'Search User...' }
    },
    list: {
      type: Array,
      required: true,
      default: () => [],
    },
    type: {
      type: String,
      default: 'light',
    },
    disabled: {
      type: Boolean,
      default: false
    },
    maxSelection: {
      type: Number,
      default: Infinity,
    },
    dropdownPosition: {
      type: String,
      default: 'dropdown',
    },
    customStyle:{
      type: Object,
      default: () =>({
        imageHeight: '60px',
        containerHeight: '40vh',
        nameFontSize: '1.05em',
        emailFontSize: '0.9em',
      }),
    },
  },

  data() {
    return {
      searchQuery: '',
      innerList: [],
    }
  },

  computed: {
    filteredList() {
      const searchQuery = this.searchQuery.toLocaleLowerCase()

      // filter by search query
      const filtered = this.innerList.filter((item) => item.payload.name.toLocaleLowerCase().includes(searchQuery) || item.payload.email.toLocaleLowerCase().includes(searchQuery))

      // display the selected items at the top
      return filtered.sort((a, b) => a.selected && !b.selected ? -1 : 1)
    },

    selectedCount() {
      return this.innerList.filter((item) => item.selected).length
    },

    isMaxSelectionReached() {
      return this.selectedCount >= this.maxSelection
    }
  },

  created() {
    this.list.forEach((payload) => {
      this.innerList.push({
        payload,
        selected: this.value.filter((u) => u.id == payload.id).length ? true : false,
      })
    })
  },

  methods: {
    toggleSelection(item) {
      if (!item.selected && this.isMaxSelectionReached) {
        return; // Prevent selection if max is reached and item is not already selected
      }
      item.selected = !item.selected;
    },

    selectUsers() {
      this.$emit('input', this.innerList.filter((item) => item.selected).map((item) => item.payload))
    }
  }
}
</script>

<style scoped lang="scss">
.user-filter {
  --image-width: 60px;
  .user-container {
    max-height: 40vh;
    overflow-y: auto;
    .user-entry {
      cursor: pointer;
      .user-placeholder {
        width: var(--image-width);
        height: var(--image-width);
        background-color: var(--bs-tertiary-bg);
        border-radius: var(--image-width);
        i.bi {
          font-size: 2em;
        }
      }
      &:hover {
        background-color: #adb5bd;
      }
      img {
        width: var(--image-width);
      }
      h2 {
        margin: 0;
        font-size: 1.05em;
      }
      p {
        margin: 0;
        font-size: 0.9em;
      }
    }
  }
}
</style>
