import { EncService } from './../../../services/enc/enc.service';
import { MatPaginator } from '@angular/material/paginator';
import { DeleteAlertComponent } from './delete-alert/delete-alert.component';
import { NewPasswordComponent } from './new-password/new-password.component';
import { MatSnackBar } from '@angular/material/snack-bar';
import { UsersResponse, UserResponse } from './../../../interfaces/users.interface';
import { UsersProfilesService } from './../../../services/users-profiles.service';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { Location } from '@angular/common';

@Component({
  selector: 'app-users-admin',
  templateUrl: './users-admin.component.html',
  styleUrls: ['./users-admin.component.css']
})
export class UsersAdminComponent implements OnInit {
  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;

  constructor(
    private usersProfilesService: UsersProfilesService, 
    private _snackBar: MatSnackBar, 
    private router: Router,
    private dialog: MatDialog,
    private _encService: EncService,
    private _location: Location,
    private _activeRoute: ActivatedRoute,
  ) { 
    this.users = [];
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.modIcon = "";
    this.modName = "";
    this.menuIcon = "";
    this.menuName = "";

    this.usersFinded = [];
  }

  ngOnInit(): void {
    this._activeRoute.queryParams.subscribe(res => {
      let infoEnc = res['info'];
      if(infoEnc == undefined || infoEnc == null || infoEnc == ""){
        this.openSnackBar('No se encontró información');
        this._location.back();
      }else{
        this.mapData(infoEnc);
      }
    });
  }

  async mapData(data: string){
    let infoDec = await this._encService.desencriptar(data);
    let infoObj = JSON.parse(infoDec);

    this.modIcon = infoObj.modIcon;
    this.modName = infoObj.modName;
    this.menuIcon = infoObj.submodule.ICONOSUBMODULO;
    this.menuName = infoObj.submodule.NOMBRESUBMODULO;
    
    this.getData();
  }

  async getData(){
    this.users = [];
    try{
      let idEnc = localStorage.getItem('idusuario');
      let idShort = await lastValueFrom(this._encService.shortEncrypt(idEnc!));
      
      let data: UsersResponse = await lastValueFrom(this.usersProfilesService.getUsers(idShort.response.encrypted, 1));
      let idDec = await this._encService.desencriptar(idEnc!);
    
      if(data.error){
        this.isLoading = false;
        this.hasError = true;
        this.errorStr = data.msg;
      }else{
        data.response.forEach((item: UserResponse) => {
          let usr: UserResponse = {
            IDUSUARIO: item.IDUSUARIO,
            NOMBRE: item.NOMBRE,
            APEPAT: item.APEPAT,
            APEMAT: item.APEMAT == null ? '-' : item.APEMAT,
            EMAIL: item.EMAIL,
            PERFIL: item.PERFIL,
            ESTATUS: item.ESTATUS
          };

          if(idDec != usr.IDUSUARIO) this.users.push(usr);
        });

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

        this.isLoading = false;
      }
    }catch(error:any){
      this.isLoading = false;
      this.hasError = true;
      this.errorStr = 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);
      }
    });
  }

  async updatePass(id: string, pass: string, passConf: string){
    try{
      let idEnc = await this._encService.encriptar(id);
      let idUser = localStorage.getItem('idusuario');
      console.log(idUser);
      
      /*
      await lastValueFrom(this.usersProfilesService.updatePwd({
        id: idEnc,
        id_user: idUser,
        password: pass,
        password_confirmation: passConf,
        linea: 1
      }));

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

  openAlert(usr: string){
    const dialogRef = this.dialog.open(DeleteAlertComponent, {
      data: {
        id: usr
      }
    });

    dialogRef.afterClosed().subscribe(async result => {
      if(result != undefined){
        if(result){
          try{
            let idEnc = await this._encService.encriptar(usr);
            let idUser = localStorage.getItem('idusuario');
            
            await lastValueFrom(this.usersProfilesService.deleteUser({
              id: idEnc,
              id_user: idUser,
              linea: 1
            }));
            
            this.openSnackBar('El usuario se eliminó correctamente');
            this.isLoading = true;
            this.getData();
          }catch(error: any){
            this.openSnackBar(error.error.msg);
          }
        }
      }
    });
  }

  openSnackBar(message: string){
    this._snackBar.open(message, "Cerrar", {
      duration: 1500
    });
  }

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

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

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

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

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

  applyFilter(event: Event){
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource!.filter = filterValue.trim().toLowerCase();

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

  goBack(steps: number){
    window.history.go(steps * -1);
  }
}
