import {
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  Input,
  OnChanges,
  OnInit,
  Output,
  SimpleChanges,
} from '@angular/core';
import { MultiselectFilterOption } from '@msfa-models/multiselect-filter-option';
import { BehaviorSubject, Observable } from 'rxjs';

@Component({
  selector: 'msfa-temporary-filter',
  templateUrl: './temporary-filter.component.html',
  styleUrls: ['./temporary-filter.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TemporaryFilterComponent implements OnInit, OnChanges {
  private _selectedAvropFilterOption$ = new BehaviorSubject<MultiselectFilterOption[]>(null);
  selectedAvropFilterOptionState$: Observable<MultiselectFilterOption[]>;

  @Input() filterLabel: string;
  @Input() filterOptions: MultiselectFilterOption[];
  @Input() selectedOptions: MultiselectFilterOption[];
  @Output() selectedOptionsChange = new EventEmitter<MultiselectFilterOption[]>();

  // THIS SHOULD BE REPLACED BY DIGI COMPONENT
  ngOnInit(): void {
    this._selectedAvropFilterOption$ = new BehaviorSubject<MultiselectFilterOption[]>(this.selectedOptions);
    this.selectedAvropFilterOptionState$ = this._selectedAvropFilterOption$.asObservable();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.selectedOptions?.currentValue) {
      this._selectedAvropFilterOption$.next(changes.selectedOptions.currentValue);
    }
  }

  isSelected(filterOption: MultiselectFilterOption): boolean {
    return this.selectedOptions?.includes(filterOption) ?? false;
  }

  setOptionState(filterOption: MultiselectFilterOption, isSelected: boolean): void {
    if (isSelected) {
      return this._selectedAvropFilterOption$.next([...(this._selectedAvropFilterOption$.value ?? []), filterOption]);
    }
    return this._selectedAvropFilterOption$.next(
      this._selectedAvropFilterOption$.value?.filter(item => item != filterOption) ?? []
    );
  }

  emitSelectedOptions(): void {
    this.selectedOptionsChange.emit(this._selectedAvropFilterOption$.value);
  }
}
