import { ChangeDetectionStrategy, Component, forwardRef, inject, input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { FormFieldContext } from '../form-field/form-field.component';
import { IconComponent } from '../icon/icon.component';
import { AppIconName } from '../icon/icon-registry';
import { TranslatePipe } from '../../../i18n/translate.pipe';

export interface VisualLayoutOption {
  value: string;
  labelKey: string;
  descKey: string;
  icon: AppIconName;
}

/**
 * Card-based replacement for a plain layout `<select>`. Same ControlValueAccessor
 * shape as app-select so it drops into existing `[ngModel]`/`[(ngModel)]` bindings,
 * but renders each option as a selectable preview card (radiogroup) instead of a
 * dropdown, so non-technical admins can recognize the layout instead of reading its name.
 */
@Component({
  selector: 'app-visual-layout-picker',
  standalone: true,
  imports: [IconComponent, TranslatePipe],
  templateUrl: './visual-layout-picker.component.html',
  styleUrl: './visual-layout-picker.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => VisualLayoutPickerComponent),
      multi: true
    }
  ]
})
export class VisualLayoutPickerComponent implements ControlValueAccessor {
  protected readonly formField = inject(FormFieldContext, { optional: true });

  readonly options = input.required<VisualLayoutOption[]>();
  readonly ariaLabel = input<string | null>(null);
  readonly disabled = input(false);

  protected value = '';
  protected isDisabled = false;

  private onChange: (value: string) => void = () => {};
  private onTouched: () => void = () => {};

  writeValue(value: string): void {
    this.value = value ?? '';
  }

  registerOnChange(fn: (value: string) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.isDisabled = isDisabled;
  }

  protected select(optionValue: string): void {
    if (this.isDisabled) {
      return;
    }
    this.value = optionValue;
    this.onChange(optionValue);
    this.onTouched();
  }

  protected activeDescription(): string | null {
    return this.options().find(option => option.value === this.value)?.descKey ?? null;
  }
}
