import { Component, forwardRef, input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

export interface RadioOption {
  value: string;
  label: string;
}

/** The ubiquitous yes/no option pair. Language-agnostic now the labels are
    localized, so it lives next to RadioOption and both wizards import it. */
export const JA_NEE: RadioOption[] = [
  { value: 'ja', label: $localize`:@@common.ja:Ja` },
  { value: 'nee', label: $localize`:@@common.nee:Nee` },
];

/** Atom: a radio group. Thin wrapper over the Utrecht/RHC radio CSS, wired as a
    form control so it works with ngModel just like the text-input atom. */
@Component({
  selector: 'app-radio-group',
  styles: [`
    .radio-option {
      display: flex;
      align-items: center;
      gap: var(--rhc-space-max-md);
      padding-block: var(--rhc-space-max-sm);
      margin: 0;
    }
    /* form-check-input floats/margins for the .form-check layout; here it's flex-aligned. */
    .radio-option .form-check-input { margin: 0; float: none; }
  `],
  template: `
    <div
      role="radiogroup"
      [attr.aria-labelledby]="name() + '-label'"
      [attr.aria-invalid]="invalid() ? 'true' : null"
      [attr.aria-describedby]="invalid() ? name() + '-error' : null">
      @for (opt of options(); track opt.value) {
        <label class="form-check-label radio-option">
          <input
            class="form-check-input"
            [class.is-invalid]="invalid()"
            type="radio"
            [name]="name()"
            [value]="opt.value"
            [checked]="value === opt.value"
            [disabled]="disabled"
            (change)="select(opt.value)"
            (blur)="onTouched()" />
          {{ opt.label }}
        </label>
      }
    </div>
  `,
  providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => RadioGroupComponent), multi: true }],
})
export class RadioGroupComponent implements ControlValueAccessor {
  options = input.required<RadioOption[]>();
  name = input.required<string>();
  invalid = input(false);

  value = '';
  disabled = false;
  onChange: (v: string) => void = () => {};
  onTouched: () => void = () => {};

  select(v: string) {
    this.value = v;
    this.onChange(v);
  }
  writeValue(v: string) { this.value = v ?? ''; }
  registerOnChange(fn: (v: string) => void) { this.onChange = fn; }
  registerOnTouched(fn: () => void) { this.onTouched = fn; }
  setDisabledState(d: boolean) { this.disabled = d; }
}
