import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  AfterViewInit,
  ViewChild,
  ElementRef,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  AfterContentChecked,
} from '@angular/core';

@Component({
  selector: 'app-delete-dropdown-fixed',
  templateUrl: './delete-dropdown-fixed.component.html',
  styleUrls: ['./delete-dropdown-fixed.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DeleteDropdownFixedComponent implements AfterViewInit, OnInit, AfterContentChecked {
  @Input() options: number[];
  @Input() selected: number;
  @Input() modalTop: number;
  @Input() idx: number;
  @Input() scrollOffset = 0;
  @Output() valueChanges: EventEmitter<number> = new EventEmitter();
  @Output() delete: EventEmitter<boolean> = new EventEmitter();
  @Output() switch: EventEmitter<boolean> = new EventEmitter();
  @ViewChild('customInput') customInput: ElementRef;
  @ViewChild('selectedDiv') selectedDiv: ElementRef;
  isOpen = false;
  inputValue: number;
  showInput = false;
  top: number;
  right: number;
  constructor(private cdrf: ChangeDetectorRef) {}

  onChange(option: number) {
    if (option === -1) {
      this.showInput = true;
      setTimeout(() => {
        this.customInput.nativeElement.focus();
      }, 500);
      return;
    }
    this.toggleDropdown();
    this.valueChanges.emit(option);
  }

  deleteItems() {
    this.delete.emit(true);
  }

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

  positionOptions() {
    if (this.selectedDiv && this.modalTop) {
      const parent = this.selectedDiv.nativeElement.getBoundingClientRect();
      this.top = parent.top - this.modalTop - parent.height;
      this.right = 115;
    }
  }

  validateInput() {
    if (this.inputValue === undefined || this.inputValue === null) {
      this.inputValue = this.selected;
    } else if (this.inputValue === 0) {
      this.delete.emit(true);
      return;
    }
    this.valueChanges.emit(this.inputValue);
    this.toggleDropdown();
    this.showInput = false;
  }

  ngAfterContentChecked(): void {
    this.positionOptions();
  }

  ngOnInit() {
    const hasPlusTenOption = this.options.findIndex((t) => t === -1) !== -1;
    if (hasPlusTenOption === false) {
      this.options.push(-1);
    }
  }

  onSwitch() {
    this.switch.emit(this.isOpen);
  }

  ngAfterViewInit(): void {
    if (this.selected > 4) {
      const el = this.selected - 1;
      const element = document.getElementById(el.toString());
      if (element) {
        element.scrollIntoView();
      }
    }
  }

  closeDropdown() {
    if (this.isOpen === true) {
      this.isOpen = false;
      this.cdrf.detectChanges();
    }
  }
}
