import { Component, Input, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Observable } from 'rxjs';
import { KeyValue } from '../../models/key-value';
import { FilterService } from '../../services/filters.service';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'fbi-select',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './select.component.html',
  styleUrl: './select.component.scss',
})
export class SelectComponent implements OnInit {
  @Input() label!: string;
  @Input() key!: string;
  @Input() data!: Observable<KeyValue[]>;

  selected: any = undefined;

  private filterService = inject(FilterService);

  ngOnInit(): void {
    this.filterService.filters$.subscribe((f: KeyValue[]) => {
      let me = (f ?? [])
        .filter((i: KeyValue) => i.key === this.key)
        .find((_) => true);
      if (me) {
        this.selected = me.value;
      } else {
        this.selected = undefined;
      }
    });
  }

  onChange(event: any): void {
    this.filterService.set(this.key, event?.target?.value);
  }
}
