import { Component, ChangeDetectionStrategy, Input, forwardRef, Pipe, PipeTransform } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { UiDropdownComponent } from '@isa-ui/dropdown';

@Component({
  selector: 'app-ui-select-input',
  templateUrl: 'select-input.component.html',
  styleUrls: ['./select-input.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => UiSelectInputComponent),
      multi: true,
    },
  ],
})
export class UiSelectInputComponent implements ControlValueAccessor {
  @Input() public options: string[] = [];
  @Input() label = '';
  @Input() labelPipe: PipeTransform;
  @Input() optionsPipe: PipeTransform;
  @Input() valuePipe: PipeTransform;

  constructor() {}

  public value: string;
  public editable = true;

  private onChange: (value: string) => void;
  private onBlur: () => void;

  handleSelect({ selectedOption, dropdown }: { selectedOption: string; dropdown: UiDropdownComponent }) {
    this.value = this.valuePipe ? this.valuePipe.transform(selectedOption) : selectedOption;
    this.onChange(this.value);
    dropdown.close();
  }

  handleBlur() {
    this.onBlur();
  }

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

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onBlur = fn;
  }
  setDisabledState(isDisabled: boolean): void {
    this.editable = !isDisabled;
  }
}
