<script setup lang="ts">
/**
 * Props-driven radio composition for boolean values. Renders a
 * RadioGroup with two items: "true" and "false". Labels default to
 * "Yes" / "No" but can be customised via `trueLabel` / `falseLabel`.
 *
 *   <RadioBoolean v-model="agreed" label="Agree?" />
 *   <RadioBoolean
 *     v-model="agreed"
 *     label="Agree?"
 *     true-label="Of course"
 *     false-label="Never"
 *     inline
 *   />
 */
import { computed } from "vue"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"
import { FieldFrame } from "@/components/ui/field-frame"

export interface RadioBooleanProps {
  modelValue?: boolean
  id?: string
  name?: string
  label?: string
  hideLabel?: boolean
  required?: boolean
  readonly?: boolean
  disabled?: boolean
  helpText?: string
  errors?: string[]
  /** Label for the "true" option. Defaults to "Yes". */
  trueLabel?: string
  /** Label for the "false" option. Defaults to "No". */
  falseLabel?: string
  /** Render both choices on the same row. */
  inline?: boolean
}

const props = withDefaults(defineProps<RadioBooleanProps>(), {
  errors: () => [],
  trueLabel: "Yes",
  falseLabel: "No",
})

const model = defineModel<boolean>("modelValue", { default: false })

const stringValue = computed<string>(() => (model.value ? "true" : "false"))

const trueId = computed(() => `${props.id ?? "radio-bool"}-true`)
const falseId = computed(() => `${props.id ?? "radio-bool"}-false`)

function onUpdate(next: unknown): void {
  const v = Array.isArray(next) ? next[0] : next
  model.value = v === "true"
}
</script>

<template>
  <FieldFrame
    :label="label"
    :required="required"
    :hide-label="hideLabel"
    :for="id"
    :help-text="helpText"
    :errors="errors"
  >
    <RadioGroup
      :model-value="stringValue"
      :name="name"
      :disabled="disabled || readonly"
      :required="required"
      :data-element-name="name ?? undefined"
      :class="inline ? 'flex flex-row gap-4' : 'grid gap-2'"
      @update:model-value="onUpdate"
    >
      <div class="flex items-center gap-2">
        <RadioGroupItem :id="trueId" value="true" />
        <Label :for="trueId" class="cursor-pointer">{{ trueLabel }}</Label>
      </div>
      <div class="flex items-center gap-2">
        <RadioGroupItem :id="falseId" value="false" />
        <Label :for="falseId" class="cursor-pointer">{{ falseLabel }}</Label>
      </div>
    </RadioGroup>
  </FieldFrame>
</template>
