import {
  Component,
  Input,
  Output,
  EventEmitter,
  ChangeDetectionStrategy,
  ViewChild,
  ElementRef,
  OnInit,
  OnDestroy,
  HostListener,
  ChangeDetectorRef,
} from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';

@Component({
  selector: 'lib-search-dropdown',
  templateUrl: './search-dropdown.component.html',
  styleUrls: ['./search-dropdown.component.scss'],
  animations: [
    trigger('fadeIn', [
      state('true', style({ opacity: 1 })),
      transition(':enter', [style({ opacity: 0 }), animate('500ms ease-in')]),
      transition(':leave', animate(200, style({ opacity: 0 }))),
    ]),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SearchDropdownComponent implements OnInit {
  @Input() options: string[];
  @Input() selected: string;
  @Output() valueChanges: EventEmitter<string> = new EventEmitter();
  @Output() search: EventEmitter<string> = new EventEmitter();
  isOpen = false;
  absolute = false;
  @ViewChild('slectedItem') element: ElementRef;
  inputValue: string;
  @Input() load = false;
  loading = false;
  _options: string[];
  @Input() left = '0';

  constructor(private cdrf: ChangeDetectorRef) {}

  ngOnInit() {}

  onChange(option: string) {
    this.valueChanges.emit(option);
    this.inputValue = '';
    this.toggleDropdown();
    if (this.load) {
      this.loading = true;
    }
  }

  onSearch(term: string) {
    this.search.emit(term);
  }

  toggleDropdown() {
    this.isOpen = !this.isOpen;
  }

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

  @HostListener('window:scroll', ['$event'])
  scrollHandler(event) {
    if (this.absolute === false) {
      this.absolute = true;
    }
  }
}
