<template>
  <div :class="`flex flex-col space-y-2 ${defaultSize}`">
    <ts-normal-text v-if="hasTitle">
      <slot name="title" />
    </ts-normal-text>
    <div
      :class="`flex relative flex-row items-center space-x-1 justify-between w-full ${customClass} `"
      :id="'container' + tabIndex"
      @focus="
        showOption = true;
        isFocused = true;
      "
      @blur="
        isFocused = false;
        showOption = false;
      "
      :tabindex="tabIndex"
    >
      <input
        ref="select"
        :value="withKey ? valueData : textValue"
        :placeholder="placeholder"
        v-if="!isMultiple"
        disabled
        :class="` ${paddings} flex-grow cursor-pointer bg-transparent placeholder-gray-600 focus input w-full filled focus:outline-none rounded-md focus:border-primary`"
      />
      <div
        v-else
        @click="
          showOption = true;
          isFocused = true;
        "
        :class="` ${paddings} flex-grow  cursor-pointer bg-transparent text-gray-600 focus input border-[1px] w-full filled focus:outline-none
		rounded-md focus:border-primary border-gray-200 bg-white`"
      >
        {{ selectedItems.length == 0 ? "Select" : "" }}
        <span v-for="(selected, index) in selectedItems" :key="index"
          >{{ getSelectedOption(selected) }}
          {{ index == selectedItems.length - 1 ? "" : ", " }}</span
        >
      </div>
      <ts-icon
        @click="
          showOption = true;
          isFocused = true;
        "
        name="dropdown"
        custom-class="md:h-[7px] h-[6px] cursor-pointer"
      />

      <div
        v-if="showOption"
        class="absolute top-[90%] flex flex-col left-0 w-full py-3 px-2 max-h-48 overflow-y-auto z-40 bg-white drop-shadow-lg"
      >
        <div
          v-for="(option, index) in options"
          :key="index"
          class="py-3 px-3 hover:bg-gray-100 flex flex-row items-center space-x-2 cursor-pointer"
          @click.stop="selectValue(option)"
        >
          <span
            :class="`h-[10px] w-[10px] rounded-full border-[1px] border-primary ${
              itemIsSelected(option.key) ? 'bg-primary' : ''
            }`"
            v-if="isMultiple"
          ></span>
          <span
            >{{ withKey ? option.key + " - " : "" }} {{ option.value }}</span
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { onMounted, ref, toRef, defineComponent } from "vue";
import TsIcon from "../TsIcon/index.vue";
import TsNormalText from "../TsTypography/normalText.vue";

export default defineComponent({
  name: "TsSelect",
  components: {
    TsIcon,
    TsNormalText,
  },
  props: {
    withKey: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: "",
    },
    options: {
      default: [],
    },
    paddings: {
      type: String,
      default: "py-4 px-3",
    },
    customClass: {
      type: String,
      default: "",
    },
    defaultValues: {
      required: false,
      default: [],
    },
    modelValue: {
      type: String || Array,
      default: false,
    },
    isMultiple: {
      type: Boolean,
      default: false,
    },
    hasTitle: {
      type: Boolean,
      default: false,
    },
    defaultSize: {
      type: String,
      default: "w-full",
    },
  },
  emits: ["update:modelValue"],
  setup(props: any, context: any) {
    const isFocused = ref(false);
    const showOption = ref(false);

    const tabIndex = Math.random();

    const valueData = toRef(props, "modelValue");

    const textValue = ref("");

    const selectedItems = ref<any>([]);

    onMounted(() => {
      if (props.defaultValues.length > 0) {
        selectedItems.value = props.defaultValues;
      }
    });

    const itemIsSelected = (inputKey: string) => {
      const item = selectedItems.value.filter((key: any) => {
        return key == inputKey;
      });

      return item.length > 0;
    };

    const selectValue = (option: any) => {
      if (props.isMultiple) {
        if (itemIsSelected(option.key)) {
          selectedItems.value = selectedItems.value.filter((key: any) => {
            return key != option.key;
          });

          return;
        }
        selectedItems.value.push(option.key);
        context.emit("update:modelValue", selectedItems.value);
      } else {
        context.emit("update:modelValue", option.key);
        if (props.withKey) {
          valueData.value = option.key;
        } else {
          valueData.value = option.value;
          textValue.value = option.value;
        }
        isFocused.value = false;
        showOption.value = false;

        document.getElementById("container" + tabIndex)?.blur();
      }
    };

    const getSelectedOption = (keyValue: any) => {
      const option = props.options.filter((eachItem: any) => {
        return eachItem.key == keyValue;
      });

      return option[0].value;
    };

    return {
      showOption,
      valueData,
      isFocused,
      selectValue,
      tabIndex,
      textValue,
      itemIsSelected,
      selectedItems,
      getSelectedOption,
    };
  },
});
</script>
