<template>
  <select
      :class="[`nice-select ${className}`]"
      :name="name"
      v-bind="props"
      @change="handleChange"
      v-on="listeners"
  >
    <option
        key="city-option-placeholder"
        :selected="!Number(defaultCurrent || options.length || 0)"
        value=""
    >{{ placeholder || $t('Select City') }}</option>

    <option
        v-for="option in options"
        :key="`city-option-${option.value}`"
        :selected="isSelected(option)"
        :value="option.value"
        class="option"
    >
      {{ option.text }}
    </option>
  </select>
</template>

<script lang="ts" setup>
import type {ISelect} from "@/types/select-d-t";

const {t} = useI18n();
const route = useRoute();

const emit = defineEmits(['change', 'update:modelValue']);
const props = defineProps({
  value: {
    type: [String, Number],
    default: undefined,
  },
  modelValue: {
    type: [String, Number],
    default: ''
  },
  defaultCurrent: {
    type: Number,
  },
  placeholder: {
    type: String,
    default: '',
  },
  className: {
    type: String,
    default: 'nice-select',
  },
  name: String,
})

const options = useState('cities_select', () => [] as ISelect[]);

const isSelected = ({value}: { value?: string }) => {
  let i = false;
  if (props.value !== undefined && String(props.value || '')) {
    // noinspection EqualityComparisonWithCoercionJS @ts-ignore
    i = String(value) == String(props.value || '');
  } else if (props.defaultCurrent !== undefined && String(props.defaultCurrent || '')) {
    // noinspection EqualityComparisonWithCoercionJS @ts-ignore
    i = String(value) == String(props.defaultCurrent || '');
  }

  return i;
}

const handleChange = (e: Event) => {
  // const target = e.target as HTMLSelectElement;
  // const value = target.value;
  // if (value) {
  //   const selectedOption = options.value.find((item) => item.value === value);
  //   if (selectedOption) {
  //     current_governorate_id.value = selectedOption.value;
  //   }
  // }

  emit('change', e);
};

const listeners = computed(() => {
  const dynamicListeners: Record<string, any> = {};
  Object.keys(props).forEach((key) => {
    if (key.startsWith('on')) {
      const eventName: string = key.slice(2).toLowerCase();
      // @ts-ignore
      dynamicListeners[eventName] = (...args: any[]) => emit(eventName, ...args);
    }
  });

  return dynamicListeners;
});

</script>