import TVoxSDK from '@telenia/tvox-client-sdk';
import { CommonModule } from '@angular/common';
import { Component, OnInit, signal } from '@angular/core';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatTableModule } from '@angular/material/table';
import { debounceTime } from 'rxjs';
import { TVoxService } from 'src/app/tvox-client-sdk.service';

@Component({
  selector: 'search',
  imports: [
    MatCardModule,
    MatListModule,
    FormsModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    CommonModule,
    MatInputModule,
    MatTableModule,
  ],
  templateUrl: './search.component.html',
  standalone: true,
})
export class SearchComponent implements OnInit {
  private client!: TVoxSDK.Client;
  protected searchInput = new FormControl();
  protected searchArray = signal<any[]>([]);
  readonly displayedColumns: string[] = ['contact', 'number'];

  constructor(private tvoxService: TVoxService) {
    this.client = this.tvoxService.getClient(); // recupero il client istanziato in precedenza all'interno del servizio 'TVoxService'
  }

  ngOnInit(): void {
    this.searchInput.valueChanges
      .pipe(debounceTime(300))
      .subscribe((searchValue) => {
        this.client.user
          // metodo per cercare contatti o numeri
          .searchContact({
            toSearch: searchValue,
            pageNumber: 1,
            pageSize: 5,
            searchMethods: 'startWith',
          })
          .then((result) => {
            let value: any[] = [];
            result
              .on('data', (data) => {
                console.log('searchContact DATA', data);
                const contactData = (data as TVoxSDK.ExternalItemContact).data;
                value.push({
                  contact: contactData.display,
                  number: contactData.numbers?.[0]?.value ?? '-',
                });
              })
              .on('error', function (error) {
                console.error('searchContact ERROR');
              })
              .on('complete', () => {
                console.log('searchContact COMPLETE');
                this.searchArray.set(value);
              });
          })
          .catch((error) => {
            console.error('searchContact ERROR', error);
          });
      });
  }
}
