import { Component, ChangeDetectionStrategy, forwardRef, Input, ChangeDetectorRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { asyncScheduler } from 'rxjs';

@Component({
  selector: 'app-ui-text-input',
  templateUrl: './text-input.component.html',
  styleUrls: ['./text-input.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => UiTextInputComponent),
      multi: true,
    },
  ],
})
export class UiTextInputComponent implements ControlValueAccessor {
  @Input() label = '';
  @Input() suffix: string;
  @Input() placeholder = '';
  @Input() fullWidth = true;

  constructor(private cdr: ChangeDetectorRef) {}

  public value: string;
  public editable = true;
  public touched = false;
  public focussed = false;

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

  handleInput() {
    this.onChange(this.value);
  }

  handleBlur() {
    asyncScheduler.schedule(() => this.handleFocus(false));
    this.onTouched();
  }

  handleFocus(isFocussed: boolean) {
    if (isFocussed) {
      this.touched = true;
    }
    this.focussed = isFocussed;
    // this.cdr.detectChanges();
  }

  writeValue(val: string): void {
    this.value = val;
  }
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
  setDisabledState(isDisabled: boolean): void {
    this.editable = !isDisabled;
  }

  reset() {
    this.writeValue('');
    this.onChange('');
  }
}
