<template>
  <div class="list-group list-button d-flex flex-column w-100 mb-2">
    <input :type="isMultiSelect ? 'checkbox' : 'radio'" :id="buttonID" :name="groupName" :value="buttonID" :aria-required="isRequired" @click="handleClick(value)" :data-focus-target="groupName">
    <label tabindex="-1" :for="buttonID" :aria-labelledby="buttonID" class="d-flex flex-column justify-content-center py-3 px-4">
      <span class="m-0" :class="textPosition">{{ buttonLabel }}</span>
      <span v-if="buttonLabelSubCopy" class="m-0 small" :class="textPosition">{{buttonLabelSubCopy}}</span>
      <span v-if="screenReaderOnlyText" class="sr-only">{{ screenReaderOnlyText }}</span>
      <loader v-if="isLoaderDisplayed && !isMultiSelect" :style="{width: `${sizeInRem}rem`, height: `${sizeInRem}rem`}" :class="[this.loaderColor, this.loaderPosition]" />
    </label>
  </div>
</template>

<script>
import { toRefs } from 'vue';
import { useField } from 'vee-validate';
import loader from "@/ux-components/loader/loader";
export default {
  name: "listButton",
  props: {
    isMultiSelect: Boolean,
    groupName: String,
    buttonLabel: [Number,String],
    buttonID: [Number,String],
    isRequired: Boolean,
    textPosition: String,
    buttonLabelSubCopy: String,
    screenReaderOnlyText: String,
    loaderEnabled: Boolean,
    loaderColor: String,
    loaderPosition: String,
    sizeInRem: [Number,String],
    value: { // Field initial value
      type: String,
      default: ""
    }
  },
  data() {
    return {
      isLoaderDisplayed: false,
    };
  },
  methods: {
    displayLoader() {
      this.isLoaderDisplayed = true;
    },
    handleClick(value) {
      if(this.loaderEnabled){
        this.displayLoader();
      }
      this.handleChange(value);
    }
  },
  components: {
    loader,
  },
  setup(props) {
    const { groupName, value } = toRefs(props);
    const inputType = props.isMultiSelect ? "checkbox" : "radio";
    const { checked, handleChange, errorMessage } = useField(groupName, undefined, {
      type: inputType,
      checkedValue: value
    });
    return {
      checked,
      handleChange,
      errorMessage,
    };
  },
};
</script>

<style lang="scss">
.list-group {
  &.list-button {
    input[type="radio"],
    input[type="checkbox"] {
      position: static; //override bootstrap
      height: 0;
    }
  }
}
</style>
