import {
  Component,
  EventEmitter,
  Input,
  OnChanges,
  OnInit,
  Output,
  SimpleChanges,
  ViewChild,
  ViewEncapsulation
} from '@angular/core'
import { OnLoadingMoreEvent } from '../autocomplete/autocomplete.component'

@Component({
  selector: 'app-soft-select',
  templateUrl: './soft-select.component.html',
  styleUrls: ['./soft-select.component.scss'],
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class SoftSelectComponent implements OnInit, OnChanges {
  @Input() inputId: string = ''
  @Input() label: string | undefined
  @Input() secondLabel: string | undefined
  @Input() value: Date | string | null = ''
  @Input() disabled: boolean = false
  @Input() type: string = 'text'
  @Input() disableSoftselect: boolean = false
  @Input() emitOnlySelected: boolean = false
  @Input() enableLoadMore: boolean = false

  @Output() valueChange: EventEmitter<string> = new EventEmitter()
  @Output() onInputEvent: EventEmitter<any> = new EventEmitter()
  @Output() focusinInput: EventEmitter<any> = new EventEmitter()
  @Output() onAutocompleteLoadingMore: EventEmitter<OnLoadingMoreEvent> =
    new EventEmitter()
  @Output() selectedLabelChange: EventEmitter<string> = new EventEmitter()

  @ViewChild('input') inputElement: any

  temp: Date | string | null = ''
  inputFocused: boolean = false

  labelSelected: LabelTypes = 'first'

  constructor() {}

  ngOnChanges(changes: SimpleChanges): void {
    if (
      changes.value &&
      changes.value.currentValue !== changes.value.previousValue
    ) {
      this.valueChange.emit(changes.value.currentValue)
    }
  }

  ngOnInit(): void {}

  autocompleteLoadingMore(event: OnLoadingMoreEvent) {
    this.onAutocompleteLoadingMore.emit(event)
  }

  onInputFired(event: any) {
    const value = event.target.value

    this.temp = value

    this.valueChange.emit(value)
    this.onInputEvent.emit(event)
  }

  onDateInputFired(value: any) {
    this.temp = value

    this.valueChange.emit(value)
    this.onInputEvent.emit(value)
  }

  onInputMouseOut() {
    if (this.disableSoftselect) return

    this.value = this.temp
    this.temp = ''
  }

  onInputMouseOver() {
    if (this.disableSoftselect) return

    this.temp = !!this.value ? this.value : ''
    this.value = ''
  }

  onFocusinInput(event: any) {
    this.focusinInput.emit(event)
  }

  onChangeLabel(label: LabelTypes) {
    this.labelSelected = label

    const selectedLabelText = label === 'first' ? this.label : this.secondLabel

    this.selectedLabelChange.emit(selectedLabelText)
  }
}

export type LabelTypes = 'first' | 'second'
