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

      <option
          v-for="option in options"
          :key="`country-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,
    default: undefined,
  },
  modelValue: {
    type: String,
    default: ''
  },
  defaultCurrent: {
    type: Number,
  },
  placeholder: {
    type: String,
    default: '',
  },
  className: {
    type: String,
    default: 'nice-select',
  },
  name: String,
});

const defaultValue = useState('default_country_id', () => '' as string);
const options = useState('countries_select', () => [] as ISelect[]);
const current_country_id = useState('current_country_id', () => "");
const governorates_select = useState('governorates_select', () => [] as ISelect[]);
const governorates_select_index = ref<string[]>([]);

// const options = computed(() => (data.value));

const isSelected = ({value}: { value?: string }) => {
  /*if (props.value !== undefined) {
    return String(value) === String(props.value || '');
  }
  if (props.defaultCurrent !== undefined) {
    return String(value) === String(props.defaultCurrent || '');
  }
  return false;*/
  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 || '');
  }/* else {
    // noinspection EqualityComparisonWithCoercionJS @ts-ignore
    i = String(value) == String(defaultValue.value);
  }*/

  return i;
}

const {
  data: dataGovernorates,
  pending: pendingGovernorates,
  error: errorGovernorates,
  execute: executeGovernorates,
} = useLazyAsyncData(
    `governorates_data_select-${current_country_id.value}`,
    (): Promise<ISelect[]> => {
      if (current_country_id.value) {
        if (governorates_select_index.value.includes(current_country_id.value)) {
          governorates_select_index.value = governorates_select_index.value.filter(item => item !== current_country_id.value);

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

      governorates_select_index.value.push(current_country_id.value);
      return current_country_id.value ?
          $axios.get(`governorates/${current_country_id.value}`)
              .then((res) => {
                governorates_select.value = res.data.data;
                return res.data.data;
              }) :
          Promise.resolve([] as ISelect[]);
    },
    {
      default: () => governorates_select.value,
      watch: [ current_country_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_country_id.value = selectedOption ? String(selectedOption.value) : '';
    // }
  }

  executeGovernorates();
      // .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;
});
</script>