import { Component, Inject, OnInit } from '@angular/core';
import { UserResponse, UsersResponse } from '../../../../interfaces/users.interface';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-panel-users',
    templateUrl: './panel-users.component.html',
    styleUrl: './panel-users.component.css',
    standalone: false
})
export class PanelUsersComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  panelName: string;

  notRelatedUsersList: UserResponse[];
  relatedUsersList: UserResponse[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _usersProfilesService: UsersProfilesService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<PanelUsersComponent>
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.panelName = '';

    this.notRelatedUsersList = [];
    this.relatedUsersList = [];
  }

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

  async init(){
    let dataDec = await this._encService.decrypt(this._data.panel);
    let dataArr = dataDec.split('|');
    
    if(dataArr.length != 2){
      this.hasError = true;
      this.errorStr = 'La información enviada tiene un formato inválido.';
      this.isLoading = false;
    }else{
      this.panelName = `${dataArr[1]} (${dataArr[0]})`;
      this.getUsers();
    }
  }

  async getUsers(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idUserDec = await this._encService.decrypt(idUser);
      let users: UsersResponse = await lastValueFrom(this._usersProfilesService.getUsers(idUser, 1));

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

      if(!this.hasError){
        for(const user of users.response){
          user.IDUSUARIO = await this._encService.decrypt(user.IDUSUARIO);
          if(!user.TIENE_PANEL && user.ESTATUS == 'Activo' && user.IDUSUARIO != idUserDec){
            this.notRelatedUsersList.push(user);
          }else if(user.TIENE_PANEL && user.ESTATUS == 'Activo' && user.IDUSUARIO != idUserDec){
            let panelArr = this.panelName.split('(').reverse();
            let idPanel = panelArr[0].replace(')', '').trim();

            let userPanelArr = user.PANEL_CONTROL.split('(').reverse();
            let idUserPanel = userPanelArr[0].replace(')', '').trim();
            if(idPanel == idUserPanel){
              this.relatedUsersList.push(user);
            }else{
              this.notRelatedUsersList.push(user);
            }
          }
        }
      }

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

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

  updateUserAssociationStatus(idUser: string, list: string){
    if(list == 'NA'){
      let userFilt = this.notRelatedUsersList.filter(user => user.IDUSUARIO == idUser);
      if(userFilt.length > 0){
        if(userFilt[0].TIENE_PANEL){
          let dialogRef = this._dialog.open(AlertComponent, {
            width: '480px',
            maxWidth: '480px',
            disableClose: true,
            data: {
              title: 'Precaución',
              icon: 'warning',
              description: 'El usuario ya cuenta con un panel de control asociado.',
              description2: '¿Realmente desea reasignar otro panel?',
            }
          });

          dialogRef.afterClosed().subscribe(res => {
            if(res == true){
              let notRelatedUsersListAux: UserResponse[] = [];
              for(const user of this.notRelatedUsersList){
                if(user.IDUSUARIO != idUser){
                  notRelatedUsersListAux.push(user);
                }else{
                  this.relatedUsersList.push(user);
                }
    
                this.notRelatedUsersList = notRelatedUsersListAux;
              }
            }
          });
        }else{
          let notRelatedUsersListAux: UserResponse[] = [];
          for(const user of this.notRelatedUsersList){
            if(user.IDUSUARIO != idUser){
              notRelatedUsersListAux.push(user);
            }else{
              this.relatedUsersList.push(user);
            }

            this.notRelatedUsersList = notRelatedUsersListAux;
          }
        }
      }
    }else{
      let userFilt = this.relatedUsersList.filter(user => user.IDUSUARIO == idUser);
      if(userFilt.length > 0){
        let userName = `${userFilt[0].NOMBRE} ${userFilt[0].APEPAT}`;
        if(userFilt[0].APEMAT != null){
          userName += ` ${userFilt[0].APEMAT}`;
        }

        userName += ` (${userFilt[0].IDUSUARIO})`
        let dialogRef = this._dialog.open(AlertComponent, {
          width: '480px',
          maxWidth: '480px',
          disableClose: true,
          data: {
            title: 'Alerta',
            icon: 'warning',
            description: `¿Está seguro de desasociar al usuario ${userName} del panel '${this.panelName}'?`,
          }
        });

        dialogRef.afterClosed().subscribe(res => {
          if(res == true){
            let relatedUsersListAux: UserResponse[] = [];
            for(const user of this.relatedUsersList){
              if(user.IDUSUARIO != idUser){
                relatedUsersListAux.push(user);
              }else{
                this.notRelatedUsersList.push(user);
              }
            }

            this.relatedUsersList = relatedUsersListAux;
          }
        });
      }
    }
  }

  async savePanelAssociatedUsers(){
    let associatedUsers: string[] = [];
    for(const user of this.relatedUsersList){
      let idAssociatedUser = await this._encService.encrypt(user.IDUSUARIO);
      associatedUsers.push(idAssociatedUser);
    }

    let associatedUsersStr = JSON.stringify(associatedUsers);
    this._dialogRef.close(associatedUsersStr);
  }
}
