<template>
  <fieldset :aria-label="ariaLabel">
    <div class="flex flex-col gap-4">
      <label
        v-for="option in options"
        :key="option.id"
        :aria-label="option.name"
        class="group relative px-5 py-4 flex items-center gap-2.5 rounded-md cursor-pointer border"
        :class="
          selectedOptionId === option.id
            ? 'border-indigo-700 outline outline-1 outline-offset-0 outline-indigo-700'
            : 'border-gray-300'
        "
      >
        <input
          type="radio"
          :name="name"
          :value="option.id"
          :checked="selectedOptionId === option.id"
          class="sr-only"
          @change="handleSelectOption(option)"
        />
        <span
          v-if="option.color"
          class="w-2 h-6"
          :style="{
            backgroundColor: getBackgroundColor(option.color),
          }"
        />
        <span class="text-sm text-gray-900">{{ option.name }}</span>
      </label>
    </div>
  </fieldset>
</template>
  
  <script>
export default {
  name: "CRadioGroup",
  props: {
    options: {
      type: Array,
      required: true,
      default: () => [],
    },
    value: {
      type: [String, Number],
      default: null,
    },
    name: {
      type: String,
      default: "radio-group",
    },
    ariaLabel: {
      type: String,
      default: "Select an option",
    },
    colorMap: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      selectedOptionId: this.value,
      defaultColorMap: {
        blue: "#dbeafe#1d4ed8",
        indigo: "#e0e7ff#247DAE",
        yellow: "#fef9c3#a16207",
        red: "#fee2e2#b91c1c",
        pink: "#fce7f3#be185d",
        green: "#dcfce7#15803d",
        gray: "#f3f4f6#374151",
      },
    };
  },
  methods: {
    handleSelectOption(option) {
      if (this.selectedOptionId !== option.id) {
        this.selectedOptionId = option.id;
        this.$emit("onChange", option);
      }
    },
    getColorCode(color) {
      const colorCode = color.split("#")[2];
      return `#${colorCode}`;
    },
    getBackgroundColor(color) {
      const colorCode = this.colorMap[color]
        ? this.colorMap[color]
        : this.defaultColorMap[color.toLowerCase()];

      const formattedColorCode = this.getColorCode(colorCode);
      return formattedColorCode;
    },
  },
};
</script>