<template>
  <label
    :aria-checked="value === model"
    :aria-disabled="isDisabled"
    :tabindex="tabIndex"
    :class="{
      'is-bordered': isBordered,
      'is-active bg-brand-darker text-white': value === model,
      'text-02 bg-white': value !== model,
      'is-disabled': isDisabled,
    }"
    @keydown.space.stop.prevent="model = isDisabled ? model : value"
    class="tao__radio-button inline-block relative user-select-none
    cursor-pointer h-5 line-height-default border-form-02"
    role="radio">
    <input
      :id="id"
      v-model="model"
      :name="name"
      :value="value"
      :disabled="isDisabled"
      class="tao__radio-button-original opacity-none absolute"
      type="radio"
      tabindex="-1">
    <span
      @keydown.stop
      class="h-full px-2 font-medium flex align-center justify-center">
      <slot />
      <template v-if="!$slots.default">
        {{ value }}
      </template>
    </span>
  </label>
</template>

<script>
// @flow

export default {
  name: 'TaoRadioButton',
  model: {
    prop: 'model',
    event: 'change',
  },
  props: {
    value: {}, // eslint-disable-line
    disabled: {
      type: Boolean,
      default: false,
    },
    name: {
      type: String,
      default: '',
    },
    id: {
      type: String,
      default: () => null,
    },
  },
  computed: {
    radioGroup() {
      let parent = this.$parent;

      while (parent) {
        if (parent.$options.name !== 'TaoRadioGroup') {
          parent = parent.$parent;
        } else {
          return parent;
        }
      }
      return false;
    },
    model: {
      get() {
        return this.radioGroup.value;
      },
      set(value: any) {
        this.radioGroup.$emit('input', value);
      },
    },
    isDisabled() {
      return this.disabled || this.radioGroup.disabled;
    },
    isBordered() {
      return this.radioGroup.border;
    },
    tabIndex() {
      return this.isDisabled ? -1 : 0;
    },
  },
};
</script>
