<template>
  <label
    :class="{
      'mm-radio-button--checked': localChecked,
      'mm-radio-button--disabled': realDisabled || realReadonly,
    }"
    class="mm-radio-button">
    <input
      v-model="localModel"
      v-bind="attrs"
      :value="value"
      type="radio"
      v-on="listeners"
      @change="handleChange" />
    <span class="mm-radio-faux">
      <span class="mm-radio-input"></span>
      <span
        v-if="label || $slots.default"
        class="mm-radio-label">
        <slot v-bind="{ label, value }">
          {{ label }}
        </slot>
      </span>
    </span>
  </label>
</template>

<script>
import input from "../../mixins/input"
import { getListeners } from "../../utils/helper"

export default {
  name: "mm-radio-button",
  mixins: [input],
  inheritAttrs: false,
  model: {
    prop: "model",
    event: "input",
  },
  inject: {
    radioGroup: {
      from: "mm-radio-group",
      default: null,
    },
  },
  props: {
    model: null,
    value: {
      type: null,
      default: true,
    },
    label: {
      type: String,
    },
    checked: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      localModel: this.model,
      localChecked: this.model === this.value || this.checked,
      listeners: getListeners(["keyup", "keydown", "keypress", "focus", "blur"], this),
    }
  },
  computed: {
    attrs() {
      return {
        ...this.$attrs,
        name: this.realName,
        disabled: this.realDisabled || this.realReadonly,
      }
    },
  },
  watch: {
    model(value) {
      this.localModel = value
    },
    localModel(value) {
      this.localChecked = value === this.value
      this.$emit("input", value)
    },
    checked: {
      handler(val) {
        this.localChecked = val
      },
    },
    localChecked: {
      handler(val) {
        if (this.checked !== val) {
          this.$emit("update:checked", val)
        }
      },
      immediate: true,
    },
  },
  methods: {
    handleChange(event) {
      if (this.radioGroup) {
        this.radioGroup.handleChange(event, this.value)
      }
    },
  },
}
</script>
