<template>
  <div className="d-flex flex-column">
    <button v-if="allowSelectAll" class="btn btn-sm btn-primary" @click="setAllSelected(true)">Select All</button>
    <button v-if="allowSelectAll" class="btn btn-sm btn-secondary ml-1" @click="setAllSelected(false)">Deselect All</button>
    <label v-for="(item, index) in localOptions" :key="`item_${index}_${item.title}`" class="p-list-item option">
      <input type="checkbox" :checked="item.selected" @change="toggleSelection(index)">
      <span class="px-2">{{ item.title }}</span>
    </label>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue'

export interface MultipleSelectOption {
  title: string;
  value?: any;
  selected?: boolean;
  itemKey?: string;
}

export default defineComponent({
  components: {
  },
  props: {
    options: {
      type: Array as PropType<MultipleSelectOption[]>,
      default: () => [],
    },
    allowSelectAll: {
      type: Boolean as PropType<boolean>,
      default: false,
    },
    maxSelection: {
      type: Number as PropType<number>,
      default: Infinity,
    },
    minSelection: {
      type: Number as PropType<number>,
      default: 0,
    },
  },

  data() {
    return {
      localOptions: [] as MultipleSelectOption[]
    }
  },
  mounted() {
    this.initializeOptions();
    this.emitSelected();
  },
  methods: {
    setAllSelected(select: boolean) {
      this.localOptions.forEach(item => {
        item.selected = select;
      });
      this.emitSelected();
    },
    toggleSelection(index: number) {
      const item = this.localOptions[index];
      item.selected = !item.selected;
      this.emitSelected();
    },
    initializeOptions() {
      this.localOptions = this.options.map(option => ({
        ...option,
        selected: option.selected || false
      }));
    },
    emitSelected() {
      const selectedItems = this.localOptions
        .filter(item => item.selected)
        .map(item => ({
          title: item.title,
          value: item.value || item.title,
          itemKey: item.itemKey
        }));

      this.$emit('input', selectedItems);
      this.$emit('change', selectedItems);
    },
  },
  watch: {
    options: {
      handler(newOptions: MultipleSelectOption[]) {
        this.localOptions = [...newOptions];
      },
      deep: true
    }
  },
})
</script>

<style lang="scss" scoped></style>