import {
  Component,
  OnInit,
  Input,
  Output,
  ViewChild,
  ElementRef,
  EventEmitter,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  ViewRef,
} from '@angular/core';
import { AutocompleteResults } from './models/autocomplete-results.model';

@Component({
  selector: 'app-search',
  template: `
    <div class="search-wrapper" [ngClass]="{ branch: branchColorMode }">
      <input
        [ngModel]="input"
        (ngModelChange)="change($event)"
        (keypress)="keyHandler($event)"
        class="search-box"
        [ngClass]="{ 'placeholder-branch': branchColorMode }"
        [placeholder]="placeholder"
        type="text"
        #search
        autofocus
      />
      <span *ngIf="error && (!load || !loading)" class="error-message">{{ error }}</span>
      <img
        (click)="clear()"
        *ngIf="input.length && (!load || !loading)"
        class="clear-icon"
        [src]="branchColorMode ? '/assets/images/close-branch.svg' : '/assets/images/close.svg'"
      />
      <img *ngIf="!load || !loading" (click)="emitSearch(input)" class="search-icon" src="/assets/images/Search_Icon.svg" />
      <div class="spinner" *ngIf="load && loading"></div>
    </div>
    <div
      class="autocomplete-wrapper"
      [ngClass]="{ 'autocompleate-ipad-padding': isIPad }"
      *ngIf="autocompleteResults.length > 0 && input && showAutocomplete === true"
    >
      <div *ngFor="let result of autocompleteResults">
        <div
          class="autocomplete-result-item align-left"
          [ngClass]="{ 'autocomplete-result-item-ipad': isIPad }"
          (click)="selectAuto(result)"
        >
          <span>{{ result.display }}</span>
        </div>
      </div>
    </div>
  `,
  styleUrls: ['./search-input.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SearchInputComponent implements OnInit {
  @Input() placeholder = '';
  @Input() input = '';
  @Input() error = '';
  @Input() showAutocomplete;
  @Input() autocompleteResults = [];
  @Input() isIPad = false;
  @Input() load = false;
  @Input() branchColorMode = false;
  @Output() inputChange = new EventEmitter();
  @Output() search = new EventEmitter();
  @Output() keypress = new EventEmitter();
  @Output() empty = new EventEmitter();
  @ViewChild('search') searchInput: ElementRef;
  loading = false;
  constructor(private cdrf: ChangeDetectorRef) {}

  ngOnInit() {}

  focus() {
    this.searchInput.nativeElement.focus();
  }

  change(text: string) {
    this.input = text;
    this.inputChange.emit(text);
  }

  public clearInput() {
    this.input = '';
    this.detectChanges();
  }

  clear() {
    this.change('');
    this.error = '';
    this.empty.emit(true);
  }

  public updateInput(text) {
    this.input = text;
    this.detectChanges();
  }

  emitSearch(input: string) {
    if (this.load) {
      this.loading = true;
      this.detectChanges();
    }
    this.search.emit(input);
  }

  selectAuto(result: AutocompleteResults) {
    this.input = result.display;
    this.search.emit(result.query);
  }

  keyHandler(event: any) {
    if (event.key === 'Enter') {
      if (this.load && this.loading) {
        return;
      }
      if (this.load) {
        this.loading = true;
        this.detectChanges();
      }
      this.search.emit(this.input);
    }
  }

  public stopLoading() {
    this.loading = false;
    this.detectChanges();
  }

  detectChanges() {
    setTimeout(() => {
      if (this.cdrf !== null && this.cdrf !== undefined && !(this.cdrf as ViewRef).destroyed) {
        this.cdrf.detectChanges();
      }
    }, 0);
  }
}
