<template>
  <label class="mm-radio">
    <input
      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",
  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,
    },
    onChange: {
      type: Function,
      default() {},
    },
  },
  data() {
    return {
      localChecked: false,
      listeners: getListeners(["keyup", "keydown", "keypress", "focus", "blur"], this),
    }
  },
  computed: {
    attrs() {
      return {
        ...this.$attrs,
        checked: this.localChecked,
        name: this.realName,
        disabled: this.realDisabled || this.realReadonly,
      }
    },
  },
  watch: {
    checked: {
      immediate: true,
      handler(value) {
        this.localChecked = value

        if (value && this.model !== this.value) {
          this.$emit("input", this.value)
        }
      },
    },
    model: {
      immediate: true,
      handler(model) {
        if (model != null) {
          this.localChecked = model === this.value
        } else {
          this.localChecked = this.checked
        }
      },
    },
  },
  methods: {
    handleChange(event) {
      const checked = event.target.checked

      this.$emit("update:checked", checked)

      if (checked) {
        this.$emit("input", this.value)
      }

      this.onChange(event, this.value)

      if (this.radioGroup) {
        this.radioGroup.handleChange(event, this.value)
      }
    },
  },
}
</script>
