import { AfterViewInit, Component, ElementRef, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core';
import { AbstractControl, FormControl } from '@angular/forms';

export interface Option {
  value: any;
  label: string
}

@Component({
  selector: 'app-select',
  templateUrl: './select.component.html',
  styleUrls: ['./select.component.scss']
})
export class SelectComponent implements OnChanges {
  _selectedOption?: Option;
  _options: Option[] = []
  _active: boolean = false;
  private _disableBlurEffect: boolean = false;
  @Input() formControl: any;
  @Input() options?: any[];
  @Input() optionLabel?: string;
  @Input() value?: any;
  @ViewChild('select', {static: true}) select?: ElementRef;
  @ViewChild('selectIcon', {static: true}) selectIcon?: ElementRef;
  @Output() onSelection: EventEmitter<any> = new EventEmitter();

  constructor(

  ) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (this.options?.length) {
      this._options = this.options.map(option => ({
        value: option,
        label: typeof this.optionLabel === 'undefined' ? undefined : option[this.optionLabel]
      } as Option));

      const selectedOption = this._options.find(option => option.value === this.value || option.value?.value === this.value);
      if (selectedOption) {
        this.setOption(selectedOption);
      }
    }
  }

  onIconClick(): void {
    if (this.select) {
      this.select.nativeElement.focus();
      this.select.nativeElement.click();
    }
  }

  setOption(selectedOption: Option): void {
    this._selectedOption = selectedOption;
    this._active = false;
    this.select?.nativeElement?.focus();
    this.onSelection.emit(this._selectedOption);
  }

  onFocus(): void {
    this._disableBlurEffect = true;
    window.setTimeout(() => this._disableBlurEffect = false, 150);
  }

  onBlur(): void {
    window.setTimeout(() => {
      if (!this._disableBlurEffect) {
        this._active = false;
      }
    }, 150);
  }
}
