<template>
  <BCol class="col-lg-6">
    <div class="form-group">
      <label class="form-label" for="country-code-select">انتخاب پیش شماره</label>
      <select
          id="country-code-select"
          class="form-select"
          v-model="country_code"
          :disabled="loading"
          aria-describedby="country-code-help"
      >
        <option value="" disabled>لطفاً یک کشور انتخاب کنید</option>
        <option
            v-for="code in countries"
            :value="code?.id"
            :key="code?.id"
        >
          {{ code?.title }}
          <template v-if="code?.country_code">({{ code?.country_code }})</template>
        </option>
      </select>
      <small id="country-code-help" class="form-text text-muted">
        کد کشور را برای شماره تلفن انتخاب کنید.
      </small>
      <div v-if="loading" class="spinner-border spinner-border-sm text-primary" role="status">
        <span class="visually-hidden">در حال بارگذاری...</span>
      </div>
    </div>
  </BCol>
</template>

<script setup>
import { ref, watch, onMounted, defineProps, defineEmits } from 'vue';
import { toast } from 'vue3-toastify';
import ApiService from '@/services/ApiService';

// Define props for v-model
const props = defineProps({
  countryCode: {
    type: [Number, String], // Allow both Number and String to handle type mismatches
    default: '',
  },
});

// Define emits for v-model
const emit = defineEmits(['update:country-code']);

// Reactive state
const countries = ref([]);
const country_code = ref(props.countryCode); // Initialize with prop value
const loading = ref(false);

// Fetch country configurations
const getConfigCountries = async () => {
  try {
    loading.value = true;
    const { data: { data, success } } = await ApiService.get('admin/country-configs');

    if (success)
      countries.value = data;

    if (props.countryCode && countries.value.some(code => code.id === props.countryCode)) {
      country_code.value = props.countryCode;
    } else {
      country_code.value = ''; // Reset if invalid
    }
  } catch (error) {
    const message = error?.response?.data?.message || 'خطا در دریافت لیست کشورها';
    toast.error(message);
  } finally {
    loading.value = false;
  }
};

// Watch for changes in country_code and emit to parent
watch(country_code, (newValue) => {
  emit('update:country-code', Number(newValue)); // Ensure emitted value is a Number
});

// Watch for prop changes to update country_code
watch(() => props.countryCode, (newValue) => {
  if (newValue && countries.value.some(code => code.id === newValue)) {
    country_code.value = newValue;
  } else {
    country_code.value = '';
  }
});

// Fetch data on component mount
onMounted(getConfigCountries);
</script>

<style scoped>
.form-group {
  position: relative;
}

.spinner-border {
  position: absolute;
  top: 50%;
  right: 10px;
  transform: translateY(-50%);
}
</style>