import { Component, OnInit, ViewChild } from '@angular/core';
import { UserResponse, UsersResponse } from '../../../interfaces/users.interface';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { SocketService } from '../../../services/socket.service';
import { FunctionsService } from '../../../services/functions.service';
import { ResourcesService } from '../../../services/resources.service';
import { UserConsultResponse } from '../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../interfaces/profile.interface';
import { Permissions } from '../../../interfaces/permissions.interface';
import { NewPasswordComponent } from './new-password/new-password.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

const ID_MODULE = "S002V01M02USPE";
@Component({
    selector: 'app-users-admin',
    templateUrl: './users-admin.component.html',
    styleUrl: './users-admin.component.css',
    standalone: false
})
export class UsersAdminComponent implements OnInit {
  public btnSmall: boolean = false;
  public txtBuscador:string;

  users: Array<UserResponse>;
  errorStr: string;
  modIcon: string;
  modName: string;
  menuIcon: string;
  menuName: string;

  isLoading: boolean;
  hasError: boolean;
  usersFinded: Array<UserResponse>;

  displayedColumns: string[] =  ['ID', 'NOMBRE', 'APEPAT', 'APEMAT', 'PERFIL', 'ESTATUS', 'EMAIL', 'ACCIONES'];
  dataSource: MatTableDataSource<UserResponse>;

  @ViewChild(MatPaginator) paginator?: MatPaginator;
  @ViewChild(MatSort) sort?: MatSort;

  usersConsultEnabled: boolean;
  regEditUserEnabled: boolean;
  blockUnblockEnabled: boolean;
  changePasswordEnabled: boolean;

  constructor(
    private _usersProfilesService: UsersProfilesService,
    private _router: Router,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _socketService: SocketService,
    private _functionsService: FunctionsService,
    private _resourcesService: ResourcesService,
  ) { 
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.users = [];
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.modIcon = "";
    this.modName = "";
    this.menuIcon = "";
    this.menuName = "";
    this.txtBuscador = '';

    this.dataSource = new MatTableDataSource();

    this.usersFinded = [];
    this.btnSmall = window.innerWidth <= 1615;
    this.usersConsultEnabled = true;
    this.regEditUserEnabled = true;
    this.blockUnblockEnabled = true;
    this.changePasswordEnabled = true;
  }

  ngOnInit(): void {
    this.getData();
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      try{
        let idUser = localStorage.getItem('idusuario')!;
        let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(idUser, idUser, 1));
        
        if(usrInfo.error){
          this._resourcesService.openSnackBar('ERR_NPE000: Ocurrió un error inesperado.');
        }else{
          let idProfDec = await this._encService.decrypt(usrInfo.response.PERFIL);
          let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

          if(idProfDec != currentProfile){
            this._router.navigate(['/sam/home']);
            return;
          }
          
          let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
          if(profileUpdated == currentProfile){
            let profile = localStorage.getItem('perfil')!;
            let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(
              profile,
              idUser,
              1
            ));

            let permArr = await this._functionsService.processPermissions(profInfo.response.PERMISOS.permissions);
            let modPerm = permArr.filter(item => item.id == 'S002V01M02USPE');
            if(modPerm.length > 0){
              let subPerm = modPerm[0].children.filter(item => item.id == 'S002V01S01GEUS');
              if(subPerm.length > 0){
                let funPerm = subPerm[0].children.filter(item => item.id == 'S002V01F01ADUS');
                if(funPerm.length > 0){
                  let usersConsultEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01COUS');
                  if(usersConsultEnabled.length > 0){
                    this.usersConsultEnabled = usersConsultEnabled[0].access > 0;
                  }

                  let regEditUserEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02RAUS');
                  if(regEditUserEnabled.length > 0){
                    this.regEditUserEnabled = regEditUserEnabled[0].access > 0;
                  }
                }
  
                let blockUnblockEnabled = subPerm[0].children.filter(item => item.id == 'S002V01F02BDAC');
                if(blockUnblockEnabled.length > 0){
                  this.blockUnblockEnabled = blockUnblockEnabled[0].access > 0;
                }

                let changePasswordEnabled = subPerm[0].children.filter(item => item.id == 'S002V01F03RECO');
                if(changePasswordEnabled.length > 0){
                  this.changePasswordEnabled = changePasswordEnabled[0].access > 0;
                }
              }
            }
          }
        }
      }catch(error: any){
        if(error.error == undefined){
          this._resourcesService.openSnackBar('ERR_PAD001: Ocurrió un error inesperado.');
        }else if(error.error.msg == undefined){
          this._resourcesService.openSnackBar('ERR_PAD002: Ocurrió un error inesperado.');
        }else{
          this._resourcesService.openSnackBar(`ERR_PAD003: ${error.error.msg}`);
        }
      }
    });

    this._socketService.refreshModules().subscribe(async () => this._functionsService.consultModuleStatus(ID_MODULE));
  }

  async getData(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";

      let idEnc = localStorage.getItem('idusuario')!;
      let data: UsersResponse = await lastValueFrom(this._usersProfilesService.getUsers(idEnc, 1));
      let idDec = await this._encService.decrypt(idEnc!);

      this.hasError = data.error;
      this.errorStr = data.msg;
    
      if(!this.hasError){
        let usersArr: UserResponse[] = [];
        for(const user of data.response){
          user.IDUSUARIO = await this._encService.decrypt(user.IDUSUARIO);
          user.APEMAT = user.APEMAT == null ? '-' : user.APEMAT;

          if(user.IDUSUARIO != idDec){
            usersArr.push(user);
          }
        }

        this.users = usersArr;
        this.dataSource = new MatTableDataSource(usersArr);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;

        let permissionsEnc = localStorage.getItem('permisos');
        let permissionsDec = '';
        if(permissionsEnc == '' || permissionsEnc == undefined || permissionsEnc == null){
          permissionsDec = '[]';
        }else{
          permissionsDec = await this._encService.decrypt(permissionsEnc!);
        }

        let permissionsArr: Permissions = JSON.parse(permissionsDec);
        if(permissionsArr.permissions != undefined){
          let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M02USPE');
          if(modPerm.length > 0){
            let subPerm = modPerm[0].children.filter(item => item.id == 'S002V01S01GEUS');
            if(subPerm.length > 0){
              let funPerm = subPerm[0].children.filter(item => item.id == 'S002V01F01ADUS');
              if(funPerm.length > 0){
                let usersConsultEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01COUS');
                if(usersConsultEnabled.length > 0){
                  this.usersConsultEnabled = usersConsultEnabled[0].access > 0;
                }

                let regEditUserEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02RAUS');
                if(regEditUserEnabled.length > 0){
                  this.regEditUserEnabled = regEditUserEnabled[0].access > 0;
                }
              }

              let blockUnblockEnabled = subPerm[0].children.filter(item => item.id == 'S002V01F02BDAC');
              if(blockUnblockEnabled.length > 0){
                this.blockUnblockEnabled = blockUnblockEnabled[0].access > 0;
              }

              let changePasswordEnabled = subPerm[0].children.filter(item => item.id == 'S002V01F03RECO');
              if(changePasswordEnabled.length > 0){
                this.changePasswordEnabled = changePasswordEnabled[0].access > 0;
              }
            }
          }
        }
      }

      this.isLoading = false;
    }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;
    }
  }

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1615;
  }

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  async openUser(action: string, user: string){
    let params = {
      action: action,
      user: user
    };

    let paramsStr = JSON.stringify(params);
    let paramsEnc = await this._encService.encrypt(paramsStr);
    
    this._router.navigate(['sam/USPE/GEUS/ADUS/crear'], {
      queryParams: {
        info: paramsEnc,
      }
    });
  }

  async blockUser(id: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let user = this.users.filter(item => item.IDUSUARIO == id)[0];
      let idEnc = await this._encService.encrypt(user.IDUSUARIO);
      let lastStatus = user.ESTATUS;
      let newStatus = lastStatus == 'Activo' ? 'Inactivo' : 'Activo';

      await lastValueFrom(this._usersProfilesService.blockUser({
        id: idUser,
        estatus: newStatus,
        id_user: idEnc,
        linea: 1
      }));

      this.getData();
      this._resourcesService.openSnackBar('El usuario fue actualizado correctamente.');
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado');
      }else  if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  openDialog(usr: string){
    const dialogRef = this._dialog.open(NewPasswordComponent, {
      data: {
        id: usr
      }
    });

    dialogRef.afterClosed().subscribe(result => {
      if(result != "" && result != undefined){
        this.updatePass(result.id, result.password, result.password_confirmation);
      }
    });
  }

  private async updatePass(id: string, pass: string, passConf: string){
    try{
      let idEnc = await this._encService.encrypt(id);
      let idUser = localStorage.getItem('idusuario');
      
      await lastValueFrom(this._usersProfilesService.updatePwd({
        id: idEnc,
        id_user: idUser,
        password: pass,
        password_confirmation: passConf,
        linea: 1
      }));

      this._resourcesService.openSnackBar('La contraseña fue actualizada correctamente.');
      this.getData();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (3).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (4).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  openAlert(idUserDel: string){
    let userDelFilt = this.dataSource!.data.filter(item => item.IDUSUARIO == idUserDel);
    if(userDelFilt.length > 0){
      let userDelName = this._functionsService.buildName(userDelFilt[0].NOMBRE, userDelFilt[0].APEPAT, userDelFilt[0].APEMAT);

      const dialogRef = this._dialog.open(AlertComponent, {
        width: '420px',
        maxWidth: '420px',
        disableClose: true,
        data: {
          title: '¡Cuidado!',
          icon: 'warning',
          description: `¿Está seguro de eliminar al usuario ${userDelName}?`,
          description2: 'Esta acción no se puede deshacer.',
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res == true){
          this.deleteUser(idUserDel);
        }
      });
    }
  }

  private async deleteUser(idUserDel: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idEnc = await this._encService.encrypt(idUserDel);
            
      await lastValueFrom(this._usersProfilesService.deleteUser({
        id: idEnc,
        id_user: idUser,
        linea: 1
      }));
      
      this._resourcesService.openSnackBar('El usuario se eliminó correctamente');
      this.getData();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }
    }
  }
}
