import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {CommonModule} from '@angular/common';

@Component({
  selector: 'sae-multi-selector',
  imports: [
    CommonModule
  ],
  templateUrl: './multi-selector.html',
  styleUrl: './multi-selector.scss'
})
export class MultiSelector implements OnInit {
  @Input() disabled: boolean = false;
  @Input() label!: string;
  @Input() availableChoices: any = [{
    label : 'aaaaaa',
    value: 'AAAAA'
  }];
  @Input() selectedChoices: any = [ ];
  @Input() displayDropdown: boolean = true;

  @Input() store: any;
  @Input() actionTypes: any;

  @Output() selectedChoicesChange = new EventEmitter<any>();
  @Output() availableChoicesChange = new EventEmitter<any>();

  searchText: string = '';

  constructor() {
      }

  ngOnInit() {
    console.log('constructor multi selector', this.label, this.availableChoices, this.selectedChoices);

  }

  onSearchInput(event: any) {
    this.searchText = (event?.target?.value || '').toLowerCase();
  }

  getFilteredSelectedChoices() {
    if (!this.searchText) {
      return this.selectedChoices || [];
    }
    return (this.selectedChoices || []).filter((c: any) =>
      (c?.label || '').toLowerCase().includes(this.searchText)
    );
  }

  getFilteredAvailableChoices() {
    if (!this.searchText) {
      return this.availableChoices || [];
    }
    return (this.availableChoices || []).filter((c: any) =>
      (c?.label || '').toLowerCase().includes(this.searchText)
    );
  }

  selectedChoicesChangeToggleItem(choice: any) {
    console.log('toggle selected choice ', choice, 'in filter ', this.label);
    this.selectedChoicesChange.emit(choice);
    console.log(choice);
    this.store.dispatch({
      type: this.actionTypes.UPDATE_FILTER,
      payload: {
        filter: this.label,
        selectedChoice: choice
      }
    })
  }

  availableChoicesChangeToggleItem(choice: any) {
    this.availableChoicesChange.emit(choice);
    console.log('toggle available choice ', choice, 'in filter ', this.label);
    this.store.dispatch({
        type: this.actionTypes.UPDATE_FILTER,
        payload: {
          filter: this.label,
          availableChoice: choice
        }
      }
    )
  }

  onClickInput() {
    if (this.disabled) {
      console.info('disabled input');
      return;
    }
    this.displayDropdown = !this.displayDropdown;
    console.log('Toggled dropdown:', this.displayDropdown);
  }
}
