import { Component, Inject, OnInit } from '@angular/core';
import { WorkGroupDetails, WorkGroupDetailsResponse, WorkGroupRelatedTeam } from '../../../../interfaces/corrective-maintenance.interface';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { lastValueFrom, map, Observable, startWith } from 'rxjs';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { WorkTeamService } from '../../../../services/personal-management/work-team.service';
import { EncService } from '../../../../services/enc.service';
import { InterventionService } from '../../../../services/personal-management/intervention.service';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { SpecialtiesListResponse } from '../../../../interfaces/specialties.interface';

@Component({
    selector: 'app-work-group-form',
    templateUrl: './work-group-form.component.html',
    styleUrl: './work-group-form.component.css',
    standalone: false
})
export class WorkGroupFormComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  action: string;
  isNew: boolean;
  workGroup: WorkGroupDetails | null;

  workTeams: any[];
  specialties: string[];

  formGroup: FormGroup;
  filteredSpecialties!: Observable<string[]>;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _workTeamsService: WorkTeamService,
    private _encService: EncService,
    private _dialogRef: MatDialogRef<WorkGroupFormComponent>,
    private _interventionService: InterventionService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.action = '';
    this.isNew = false;
    this.workGroup = null;

    this.workTeams = [];
    this.specialties = [];

    this.formGroup = new FormGroup({
      idWorkGroup: new FormControl({ value: '', disabled: true }),
      workGroupName: new FormControl('', [Validators.required, Validators.minLength(8), Validators.maxLength(50)]),
      relatedTeams: new FormControl([], [Validators.required, Validators.minLength(2)]),
      specialty: new FormControl('', [Validators.required, Validators.minLength(8), Validators.maxLength(100)])
    });
  }

  ngOnInit(): void {
    this.action = this._data.action == 'new' ? 'Registrar' : 'Editar';
    this.isNew = this._data.action == 'new';

    if(this.isNew){
      this.getWorkTeams();
    }else{
      this.getWorkGroup();
    }

    this.filteredSpecialties = this.formGroup.controls['specialty'].valueChanges.pipe(
      startWith(''),
      map(value => this._filterSpecialties(value || ''))
    );
  }

  private _filterSpecialties(value: string): string[]{
    const filterValue = value.toLowerCase();
    return this.specialties.filter(option => option.toLowerCase().includes(filterValue));
  }

  async getWorkGroup(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let workGroup: WorkGroupDetailsResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkGroup(
        this._data.idWorkGroup,
        idUser,
        1
      ));

      this.hasError = workGroup.error;
      this.errorStr = workGroup.msg;

      if(this.hasError){
        this.isLoading = false;
      }else{
        let idDec = await this._encService.decrypt(workGroup.response.ID_GRUPO);
        this.formGroup.controls['idWorkGroup'].setValue(idDec);
        this.formGroup.controls['workGroupName'].setValue(workGroup.response.NOMBRE_GRUPO);
        this.formGroup.controls['specialty'].setValue(workGroup.response.ESPECIALIDAD);

        this.workGroup = workGroup.response;
        this.getWorkTeams();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (1).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (2).';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async getWorkTeams(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let workTeams = await lastValueFrom(this._workTeamsService.getConsultOfWorkteams(idUser, 1));

      this.hasError = workTeams.error;
      this.errorStr = workTeams.msg;

      if(this.hasError){
        this.isLoading = false;
      }else{
        let selectedTeams: WorkGroupRelatedTeam[] = [];
        if(this.workGroup != null){
          let relatedTeams: WorkGroupRelatedTeam[] = JSON.parse(this.workGroup.EQUIPOS_RELACIONADOS);
          for(const team of relatedTeams){
            team.ID_EQUIPO = await this._encService.decrypt(team.ID_EQUIPO);
            selectedTeams.push(team);
          }
        }

        let workTeamsArr: any[] = [];
        for(const workTeam of workTeams.response){
          let idDec = await this._encService.decrypt(workTeam.WORKTEAM_ID);

          if(this.workGroup != null){
            let teamsValue = this.formGroup.controls['relatedTeams'].value;
            let teamFilt = selectedTeams.filter(team => team.ID_EQUIPO == idDec);
            if(teamFilt.length > 0){
              teamsValue.push(workTeam.WORKTEAM_ID);
            }
            
            this.formGroup.controls['relatedTeams'].setValue(teamsValue);
          }
        
          workTeam.NAME = `${workTeam.NAME} (${idDec})`;
          if(workTeam.STATUS == 'Activo'){
            workTeamsArr.push(workTeam);
          }
        }

        this.workTeams = workTeamsArr;
        this.getRegisteredSpecialties();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (3).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (4).';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async getRegisteredSpecialties(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let specialties: SpecialtiesListResponse = await lastValueFrom(this._interventionService.getSpecialties(idUser, 1));

      this.hasError = specialties.error;
      this.errorStr = specialties.msg;

      if(!this.hasError){
        let specialtiesArr: string[] = [];
        for(const specialty of specialties.response){
          let specialtyCodeDec = await this._encService.decrypt(specialty.CODIGO_ESPECIALIDAD);
          specialtiesArr.push(`${specialtyCodeDec} - ${specialty.NOMBRE_ESPECIALIDAD}`);
        }

        this.specialties = specialtiesArr;
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (5).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (6).';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async saveFormGroup(){
    let formValue = this.formGroup.getRawValue();
    let formStr = JSON.stringify(formValue);
    let formEnc = await this._encService.encrypt(formStr);

    this._dialogRef.close(formEnc);
  }
}
