import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { map } from 'rxjs';
import { Cid } from 'src/app/models/cid';
import { listPacienteService } from 'src/app/services/list-paciente/list-paciente.service';


@Component({
  selector: 'app-modal-cid',
  templateUrl: './modal-cid.component.html',
  styleUrls: ['./modal-cid.component.css'],
})
export class ModalCIDComponent implements OnInit  {

  cids: Cid[] = []
  termoPesquisa: string = '';
  searchQuery: any;
  searchResults: any[] = [];

  constructor(
    private cidService: listPacienteService,
    public dialogRef: MatDialogRef<ModalCIDComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {}

  ngOnInit(): void {
    this.getCids();
    
  }

  getCids(): void {
    this.cidService.getAllCids().subscribe((data) => {
      this.cids = data;
    });
  }
  
  onClose(): void {
    this.dialogRef.close();
  }

  loadCid() {
    this.cidService.getAllCids().subscribe(
      (response) => {
        this.cids = response;
      },
      (error) => {
        console.error('Erro ao obter os pacientes', error);
      }
    );
  }
  
  buscarCidbyCodigo(codigo: string) {
    this.cidService.getCidByCode(codigo).subscribe(
      (response) => {
        this.cids = response;
      },
      (error) => {
        console.error('Erro ao obter o cid por código', error);
      }
    );
  }
  
  onSearch(event: Event) {
    event.preventDefault();
  
    const codigo = this.searchQuery.trim();
    if (this.cids && Array.isArray(this.cids)) {
    let found = this.cids.filter(f => f.codigo.includes(codigo));
  
    if (found.length > 0 && codigo !== "") {
      this.searchResults = found;
    } else {
      this.searchResults = [];
    }
  }
  }

 

}
