<script setup lang="ts">
import SelectList from "#adata-ui/components/elements/select/ui/select-list.vue";
import SelectButton from "#adata-ui/components/elements/select/ui/select-button.vue";
import AInput from '~/components/forms/input/standard/AInputStandard.vue'
import AButton from "#adata-ui/components/elements/button/AButton.vue";


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

type Props = {
  label: string
  required?: boolean
  options: Option[]
  keyToSelect?: keyof Option
  clearable?: boolean
  disabled?: boolean
  // error?: string | string[]
  // startIcon?: object
  searchable?: boolean
  simpleSearch?: boolean
  searchLabel?: string
  searchKey?: keyof Option
  multiple?: boolean
  name: string
  title: string
  showCount: boolean
  buttonClass?: string
}

type Emits = {
  (e: 'onChange', option?: Option[]): void
}

const props = withDefaults(defineProps<Props>(), {
  keyToSelect: 'id',
  clearable: true,
  searchLabel: 'Поиск...',
  searchKey: 'name',
  multiple: false,
  showCount: true,
  buttonClass: 'border-deepblue-50 bg-deepblue-50 dark:border-gray-900 dark:bg-gray-200/5'
})

const emits = defineEmits<Emits>()
const searchValue = defineModel<string>('search', {default: ''})
const wrapper = ref<HTMLDivElement | null>(null)
const isOpen = defineModel<T | null | any>('open', {
  default: false
})
const selectedData = ref<any[]>([])
const formatData = (data: Option[], key: keyof Option) => {
  if (!data) return undefined;
  return data.map(el => key ? el[key] : el);
};

const formattedSelect = computed(() => {
  if (props.multiple) {
    return formatData(selectedData.value, props.keyToSelect);
  } else {
    const selected = selectedData.value[0];
    return selected ? selected[props.keyToSelect] : null;
  }
});
const modelValue = defineModel<(any[])>();

//set default data
if (modelValue.value || modelValue.value?.length) {
  if (props.multiple) {
    selectedData.value = props.options.filter(el => {
      return modelValue.value.includes(el[props.keyToSelect]);
    });
  } else {
    const selectedItem = props.options.find(el => {
      return el[props.keyToSelect] == modelValue.value;
    });
    if (selectedItem) {
      selectedData.value = [selectedItem];
    }
  }
} else {
  selectedData.value = []
}

watch(
  () => selectedData,
  () => {
    modelValue.value = formattedSelect.value
    emits("onChange", modelValue.value)
  },
  {deep: true, immediate: true}
)
const reset = () => {
  selectedData.value = []
}
defineExpose({
  reset
})
</script>

<template>
  <a-slideover
    v-model="isOpen"
    :name="name"
    position="bottom"
    size="auto"
  >
    <template #header>
      <div class="pt-4 px-2 flex flex-col justify-between gap-3">
        <div class="flex items-center" :class="{'justify-center':!showCount, 'justify-between': showCount}">
          <h4 class="heading-04">
            {{title}}
          </h4>
          <p v-if="showCount" class="text-xs text-blue-500">
            Выбрано: {{ selectedData?.length }}
          </p>
        </div>
        <a-input
          v-if="searchable"
          v-model="searchValue"
          :label="searchLabel"
          size="sm"
        />
      </div>
    </template>
    <div class="flex flex-col justify-between ">
      <div
        class="mt-1 w-full h-full bg-white p-2 border rounded-md dark:bg-gray-900 overflow-y-auto"
      >
        <slot
          name="options"
          :options="options"
        >
          <ul class="h-[280px]">
            <select-list
              v-model:selected="selectedData"
              v-model:search-value="searchValue"
              :multiple="multiple"
              :options="options"
              :search-by="searchKey"
              :simple-search="simpleSearch"
            />
          </ul>
        </slot>
      </div>
      <div class="flex gap-2 p-4 justify-self-end w-full">
        <slot name="buttons">
          <a-button
            class="w-full"
            view="outline"
            variant="gray"
            @click="reset"
          >
            Сбросить
          </a-button>
          <a-button
            class="w-full"
            @click="isOpen = false"
          >
            Выбрать
          </a-button>
        </slot>
      </div>
    </div>

  </a-slideover>
  <div
    ref="wrapper"
    class="relative w-full rounded-md text-sm"
  >
    <a-select-row
      v-model:selected-items="selectedData"
      v-model:is-open="isOpen"
      :clearable="clearable"
      :disabled="disabled"
      multiple
      :label="label"
      :btn-class="buttonClass"
    />
  </div>
</template>
