<template>
  <div :class="[fieldClasses, wrapperClass]" @click="onSelectOption">
    <input
      v-bind="$attrs"
      :id="enhancedId"
      type="radio"
      class="n-radio-field"
      :value="value"
      :disabled="disabled"
      :checked="isRadioChecked"
    />

    <label v-if="label" :for="enhancedId" :class="labelClasses">
      {{ label }}
    </label>
  </div>
</template>

<script>
import { defineComponent } from "vue";
import { v4 as uuidv4 } from "uuid";

export default defineComponent({
  name: "NRadio",
  inject: {
    groupSelectedValue: {
      from: "groupSelectedValue",
      default: "",
    },
    onForceUpdate: {
      from: "onForceUpdate",
      default: undefined,
    },
  },
  inheritAttrs: false,
  props: {
    value: undefined,
    label: {
      type: String,
      default: "",
    },
    id: {
      type: String,
      default: "",
    },

    wrapperClass: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    enhancedId() {
      const { id } = this;

      return id || uuidv4();
    },
    isRadioChecked() {
      const { groupSelectedValue, value } = this;
      const checked = String(value) === String(groupSelectedValue);
      const shouldBeActive = Boolean(groupSelectedValue);

      return shouldBeActive && checked;
    },
    fieldClasses() {
      const { disabled, isRadioChecked } = this;
      let classes =
        "pkg-base-n-radio n-px-3 n-py-2 n-radius-md n-flex n-align-center";

      if (disabled) {
        classes += " n-radio--disabled";
      }

      if (isRadioChecked) {
        classes += " n-radio--active n-bg-primary-5 ";
      } else {
        classes += " n-bg-white";
      }

      return classes;
    },
    labelClasses() {
      const { isRadioChecked } = this;

      let classes =
        "n-position-relative n-flex n-align-center n-gap-2 n-radio-label n-text-body2 n-font-normal";

      if (isRadioChecked) {
        classes += " n-color-primary-dark";
      } else {
        classes += " n-color-main-font";
      }

      return classes;
    },
  },
  methods: {
    onSelectOption() {
      if (!this.disabled) {
        const { value, onForceUpdate, isRadioChecked } = this;
        // ! update only if the radio is not selected
        if (!isRadioChecked) {
          if (onForceUpdate) {
            onForceUpdate(value);
          }

          this.$emit("change", value);
        }
      }
    },
  },
});
</script>

<style scoped>
@import url("./n-radio.css");
</style>
