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

    <option
        v-for="option in options"
        :key="`governorate-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 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 current_governorate_id = useState('current_governorate_id', (): string | undefined => undefined);
const options = useState('governorates_select', () => [] as ISelect[]);
const cities_select = useState('cities_select', () => [] as ISelect[]);
const cities_select_index = ref<string[]>([]);

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 {
  data: dataCitise,
  pending: pendingCitise,
  error: errorCitise,
  execute: executeCitise,
} = useLazyAsyncData(
    `cities_data_select-${current_governorate_id.value}`,
    (): Promise<ISelect[]> => {
      if (current_governorate_id.value !== undefined) {
        if (cities_select_index.value.includes(current_governorate_id.value)) {
          cities_select_index.value = cities_select_index.value.filter(item => item !== current_governorate_id.value);

          return Promise.resolve([] as ISelect[]);
        }

        cities_select_index.value.push(current_governorate_id.value);
      }

      return current_governorate_id.value ?
          $axios.get(`cities/${current_governorate_id.value}`)
              .then((res) => {
                cities_select.value = res.data.data;
                return res.data.data;
              }) :
          Promise.resolve([] as ISelect[]).then((res) => cities_select.value = []);
    },
    {
      default: () => cities_select.value,
      watch: [current_governorate_id],
      immediate: false,
      server: false
    }
);

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 ? String(selectedOption.value) : undefined;
    // }
  } else {
    current_governorate_id.value = undefined
  }

  executeCitise()
      // .then(() =>
          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;
});

// watch(
//     options,
//     (newVal) => {
//       console.log('options changed to: ', newVal);
//     },
//     {immediate: true}
// )
</script>