<template>
  <RadioButton
    v-for="(item, ix) of options"
    :key="item.value + '_' + ix"
    :group="name"
    :label="item.text"
    :label-first="labelFirst"
    :inline="inline"
    :model-value="refs[ix].value"
    @update:model-value="onChanged(ix, $event)"
  />
</template>

<script setup lang="ts">
import { ref, watch, PropType } from 'vue';
import { SelectOption } from '@/types/custom-types';
import RadioButton from './radio-button.vue';

const refs = ref<{ value: boolean }[]>([]);

const props = defineProps({
  options: {
    type: Array as PropType<SelectOption[]>,
    required: true,
  },
  modelValue: {
    type: [String, Number, Boolean],
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
  labelFirst: Boolean,
  inline: Boolean,
});
const emit = defineEmits(['update:modelValue']);

const onChanged = (ix: number, value: boolean) => {
  if (ix >= 0 && ix < refs.value.length) {
    refs.value[ix].value = value;
    if (ix < props.options.length) {
      emit('update:modelValue', props.options[ix].value);
    }
  }
};

watch(
  () => props.options,
  val => {
    const arr: { value: boolean }[] = [];
    for (const option of val) {
      const value = option.value === props.modelValue;
      arr.push({ value });
    }
    refs.value = arr;
  },
  { immediate: true }
);

watch(
  () => props.modelValue,
  val => {
    const ix = props.options.findIndex(x => x.value === val);
    if (ix >= 0 && ix < refs.value.length) {
      refs.value.forEach(x => (x.value = false));
      refs.value[ix].value = true;
    }
  }
);
</script>
