import { Component, OnInit } from '@angular/core';
import { DropDownFilterSettings } from '@progress/kendo-angular-dropdowns';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { UserService } from 'src/app/services/user.service';
import { process } from '@progress/kendo-data-query';
import { AnimationOptions } from 'ngx-lottie';

@Component({
  selector: 'app-permission-user',
  templateUrl: './permission-user.component.html',
  styleUrls: ['./permission-user.component.scss']
})

export class PermissionUserComponent implements OnInit {

  /* Header */
  public userName: string;
  public storeName: string;
  users: any[] = [];
  public checkedKeys: any[] = [];
  public data: any[] = [];
  public userSelected: any;
  public children = (dataItem: any): Observable<any[]> => of(dataItem.items);
  public hasChildren = (dataItem: any): boolean => !!dataItem.items;
  public permissions: any[] = [];
  public isUserLoading = false;
  public loadingIcon = '';
  public isLoading = false;
  public infoMessage = 'Por favor, selecione um usuário para carregar as permissões.';

  public lottieOptions: AnimationOptions = {
    path: 'assets/animations/no-data.json',
  };

  public lottieStyles = {
    width: '300px',
    height: '300px',
  };

  constructor(private readonly authService: AuthService,
    private readonly userService: UserService) { }

  ngOnInit() {
    this.userName = this.authService.getUserName();
    this.storeName = this.authService.getStoreName();
    this.userService.getUsers()
      .pipe(
        map((users) => {
          this.users = users;
        }))
      .subscribe();
    
      if (!this.userSelected) {
      this.infoMessage = 'Nenhum usuário está selecionado.';
    }
    this.loadUsers();
  }

  loadUsers() {
    this.isUserLoading = true; 
    this.userService.getUsers()
      .pipe(
        map((users) => {
          this.users = users;
          this.isUserLoading = false; 
        }),
        catchError((error) => {
          console.error('Erro ao carregar usuários:', error);
          this.isUserLoading = false;
          return of([]);
        })
      )
      .subscribe();
  }

  logout() {
    this.authService.logout();
  }

  public filterSettings: DropDownFilterSettings = {
    caseSensitive: false,
    operator: "contains",
  };

  public valueNormalizer = (text: Observable<string>) =>
    text.pipe(
      map((content: string) => {
        return {
          value: this.permissions[this.permissions.length - 1]?.value + 1 || 1,
          text: content,
        };
      })
    );

  forceUppercase(event: Event): void {
    const inputElement = event.target as HTMLInputElement;
    if (inputElement && inputElement.value) {
      inputElement.value = inputElement.value.toUpperCase();
    }
  }

  setUserSelected(user: any) {
    console.log(user);
    this.userSelected = user;

    if (!user) {
      this.permissions = [];
      this.checkedKeys = [];
      this.infoMessage = 'Por favor, selecione um usuário válido.';
    } else {
      this.checkedKeys = [];
      this.infoMessage = '';
    }
  }

  getPermissionUser() {
    if (!this.userSelected) {
      console.warn('Nenhum usuário selecionado. Não é possível buscar permissões.');
      this.lottieOptions = { path: 'assets/animations/no-data.json' };
      return;
    }

    this.isLoading = true;
    this.lottieOptions = { path: 'assets/animations/loading.json' };

    this.userService.getPermissionUser(this.userSelected.userId)
      .pipe(
        map((permissions) => {
          this.permissions = permissions;
          this.loadPermissions(this.permissions);

          // If permissions are found, stop the loading animation
          this.isLoading = false;
          this.lottieOptions = permissions.length > 0
            ? { path: 'assets/animations/no-data.json' }
            : { path: 'assets/animations/no-data.json' };
        }),
        catchError((error) => {
          console.error('Erro ao carregar permissões do usuário:', error);
          this.isLoading = false; // Stop loading state
          this.lottieOptions = { path: 'assets/animations/no-data.json' }; // Error or no data animation
          return of([]); // Default return value in case of error
        })
      )
      .subscribe();
  }

  savePermissions() {
    const permissionsId: number[] = [];
    const atividades: any[] = [];
    const actions: any[] = [];
    for (const key of this.checkedKeys) {
      const ids = key.split("_");
      if (ids.length > 2) {
        const module = this.permissions[ids[0]];
        const atividade = module.items[ids[1]];
        const action = atividade.items[ids[2]];
        if (action != undefined) {
          actions.push(action);
        }
      } else {
        const module = this.permissions[ids[0]];
        const atividade = module.items[ids[1]];
        if (atividade != undefined) {
          atividades.push(atividade);
        }
      }
    }
    const updatePermissions = { atividades: atividades, actions: actions };
    const userId = this.userSelected.userId;

    this.userService.updatePermissionUser(userId, updatePermissions);
  }

  loadPermissions(data: any) {
    this.checkedKeys = [];
    data.filter(permission => permission.allow == 'S')
      .forEach(permissionModule => {
        let indice_modulo = -1;
        let indice_atividade = -1;
        permissionModule.items
          .filter(permissionAtividade => permissionAtividade.allow == 'S')
          .forEach(permissionAtividade => {
            indice_modulo++;
            indice_atividade++;
            this.checkedKeys.push(`${indice_modulo}_${indice_atividade}`);
          });
      });
  }
}
