<script setup lang="ts">
import AInput from '~/components/forms/input/standard/AInputStandard.vue'

import {isEqual} from 'lodash-es'


defineOptions({
  name: 'SelectList'
})
type Option = {
  id: string | number
  name: string
}

interface Props {
  searchable?: boolean
  simpleSearch?: boolean
  searchLabel?: string
  searchBy?: keyof Option
  multiple?: boolean
  options: Option[]
}

type Emits = {
  (e: 'select', data: Option[]): void
}

const props = withDefaults(defineProps<Props>(), {
  searchable: false,
  multiple: true,
  searchLabel: 'Поиск...',
  searchBy: 'name'
})
const emits = defineEmits<Emits>()
const selected = defineModel<Option[]>('selected')
const searchValue = defineModel<string>('searchValue', {default: ''})

const setData = (option: Option) => {
  const index = selected.value.findIndex((selectedOption) => selectedOption.id === option.id);

  if (index === -1) {
    // Добавить данные, если они не существуют в массиве selected
    if (props.multiple) {
      selected.value.push(option);
    } else {
      selected.value = [option];
    }
  } else {
    // Удалить данные, если они уже существуют в массиве selected
    selected.value.splice(index, 1);
  }
  emits('select', selected.value)
};
const isSelected = (option: Option) => {
  return selected.value.some((selectedOption) => isEqual(selectedOption, option));
};
const formattedOptions = computed(() => {
  if (!props.options) return []
  if (props.simpleSearch) {
    return props.options.filter(el => el[props.searchBy].toString().includes(searchValue.value))
  }
  return props.options
})
</script>

<template>
  <div class="flex flex-col gap-2 justify-items-start">
    <div
      v-if="searchable"
      class="p-1"
    >
      <a-input
        v-model="searchValue"
        :label="searchLabel"
        size="sm"
        color="gray"
        clearable
      />
    </div>
    <template
      v-for="option in formattedOptions"
      :key="option.id"
    >
      <button
        class="flex w-full items-center justify-between px-4 py-1.5 text-start hover:bg-deepblue-50 dark:bg-[#E3E5E80D] bg-white"
        @click="setData(option)"
      >
        {{ option.name }}
        <span v-if="isSelected(option)">
          <a-icon-check style="color: #0070eb"/>
        </span>
      </button>
    </template>
  </div>
</template>

<style scoped>

</style>
