<script setup lang="ts">
/**
 * Props-driven radio-group composition. Composes the shadcn-vue
 * `RadioGroup` primitive with `FieldFrame` chrome.
 *
 *   <RadioOption v-model="size" :options="[...]" label="Size" />
 */
import { computed } from "vue"
import type { SelectOptionLike } from "@/definitions/shared/select-options"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"
import { FieldFrame } from "@/components/ui/field-frame"

export interface RadioOptionProps {
  modelValue?: string | number | null
  options?: SelectOptionLike[]
  id?: string
  name?: string
  label?: string
  hideLabel?: boolean
  inline?: boolean
  required?: boolean
  readonly?: boolean
  disabled?: boolean
  helpText?: string
  errors?: string[]
}

const props = withDefaults(defineProps<RadioOptionProps>(), {
  errors: () => [],
  options: () => [],
})

const model = defineModel<string | number | null>("modelValue")

interface NormalisedOption {
  label: string
  value: string
  disabled: boolean
}

function normaliseOption(opt: SelectOptionLike): NormalisedOption {
  if (typeof opt === "string") {
    return { label: opt, value: opt, disabled: false }
  }
  return {
    label: opt.label,
    value: String(opt.value),
    disabled: Boolean(opt.disabled),
  }
}

const normalised = computed<NormalisedOption[]>(() =>
  (props.options ?? []).map(normaliseOption),
)

const groupValue = computed<string | undefined>(() => {
  if (model.value === undefined || model.value === null) {
    return undefined
  }
  return String(model.value)
})

function onUpdate(next: unknown): void {
  if (next === undefined || next === null) {
    model.value = null
    return
  }
  if (typeof next === "string" || typeof next === "number") {
    model.value = next
    return
  }
  model.value = String(next)
}
</script>

<template>
  <FieldFrame
    :label="label"
    :required="required"
    :hide-label="hideLabel"
    :help-text="helpText"
    :errors="errors"
  >
    <RadioGroup
      :model-value="groupValue"
      :name="name"
      :disabled="disabled || readonly"
      :required="required"
      :data-element-name="name ?? undefined"
      :class="inline ? 'flex flex-row flex-wrap gap-4' : 'grid gap-2'"
      @update:model-value="onUpdate"
    >
      <div
        v-for="opt in normalised"
        :key="opt.value"
        class="flex items-center gap-2"
      >
        <RadioGroupItem
          :id="`${id ?? 'radio'}-${opt.value}`"
          :value="opt.value"
          :disabled="opt.disabled"
        />
        <Label
          :for="`${id ?? 'radio'}-${opt.value}`"
          class="cursor-pointer"
        >
          {{ opt.label }}
        </Label>
      </div>
    </RadioGroup>
  </FieldFrame>
</template>
