<template>
  <SelectWrapper
    class="space-select"
    v-model="state.keyword"
    :selected-item="state.selectedItem"
    :placeholder="props.placeholder"
    :label="props.label"
    :error="props.error"
    :search="props.search"
    :disabled="props.disabled"
    @open="open"
    @close="close"
  >
    <ul class="main h600" v-show="state.active">
      <li class="search" v-if="props.search">
        <SpaceInput
          label=""
          :placeholder="$t('common.search')"
          v-model="state.keyword"
        >
          <SpIcon name="search" />
        </SpaceInput>
      </li>

      <li
        v-for="(item, index) in filteredList"
        :key="index"
        :class="{ selected: state.selectedId === item.id }"
      >
        <div class="item" @click="selectItem(index)">
          <RadioIcon
            v-if="props.radioIcon"
            class="mr-4"
            :active="state.selectedId === item.id"
          />
          <span>{{ item.title }}</span>
        </div>
      </li>
    </ul>
  </SelectWrapper>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  onMounted,
  PropType,
  reactive,
  watch,
} from "vue";
import { SelectInterface } from "@/models";
import FormMixin from "@/mixins/FormMixin";
export default defineComponent({
  mixins: [FormMixin],
  props: {
    list: {
      type: Array as PropType<SelectInterface[]>,
      default: [],
    },
    radioIcon: {
      type: Boolean,
      default: false,
    },
    modelValue: {
      default: "",
    },
  },
  setup(props: any, { emit }) {
    const state = reactive<{
      active: boolean;
      keyword: string;
      selectedItem: {
        title: string;
        imgUrl?: string;
      } | null;
      selectedId: any;
    }>({
      active: false,
      keyword: "",
      selectedItem: null,
      selectedId: null,
    });

    const filteredList = computed((): SelectInterface[] => {
      if (state.keyword.length <= 0) {
        return props.list;
      }
      return props.list.filter((item: any) =>
        item.title.toLowerCase().includes(state.keyword.toLowerCase())
      );
    });

    const selectItem = (index: number): void => {
      state.selectedItem = {
        title: filteredList.value[index].title,
      };
      state.selectedId = filteredList.value[index].id;
      emit("update:modelValue", state.selectedId);
    };

    const open = (): void => {
      state.keyword = "";
      state.active = true;
    };

    const close = (): void => {
      state.active = false;
    };

    const setValue = (): void => {
      if (typeof props.modelValue === "object") {
        filteredList.value.find((item, index) => {
          for (const key in props.modelValue) {
            if (item.id[key] !== props.modelValue[key]) {
              return false;
            }
          }

          selectItem(index);
          return true;
        });
      } else {
        filteredList.value.find((item, index) => {
          if (item.id === props.modelValue) {
            selectItem(index);
          }
        });
      }
    };

    onMounted((): void => {
      if (props.modelValue !== "undefined" && props.modelValue !== null) {
        setValue();
      }
    });

    watch(
      (): any => props.modelValue,
      (newVal: any, oldVal: any): void => {
        if (newVal !== null && typeof newVal !== "undefined") {
          if (newVal !== oldVal) {
            setValue();
          }
        } else {
          state.selectedId = null;
          state.selectedItem = null;
        }
      }
    );

    return {
      filteredList,
      selectItem,
      open,
      close,
      state,
      props,
    };
  },
});
</script>
