import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslatePipe } from '@ngx-translate/core';
import { ToastrService } from 'ngx-toastr';
import { takeUntil } from 'rxjs';
import { Unsub } from '../../../../shared/class/unsub.class';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-edit-roles',
  templateUrl: './edit-roles.component.html',
  styleUrls: ['./edit-roles.component.scss'],
  standalone : true,
  imports: [AdminPageHeaderComponent, TranslatePipes, FormsModule]
})
export class EditRolesComponent extends Unsub implements OnInit {
  @ViewChild('checkall') checkall!:ElementRef;
  user;
  id: any;
  permissionListlen!: number;
  permission: any;
  checkedRoles: any[] = [];
  checkAllBtn!: boolean;
  public sendingResponse: { [key: string]: boolean } = {};
  constructor(
    private adminService: AdminService,
    private toastr: ToastrService,
    private activeRoute: ActivatedRoute,
    private router: Router,
    private translate: TranslatePipe,
    loaderService: LoaderService
  ) {
    /**
    * This code calls the constructor of the parent class in a subclass. 
    * The super() function is used to initialize the parent class and allows access to its properties and methods. 
    * By calling  super(), the subclass can inherit and use the functionality of the parent class.
    **/
    super(loaderService);
  }

  ngOnInit(): void {
    this.activeRoute.paramMap.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (params) => {
        this.id = params.get('id');
        this.loaderService.showLoader();
        this.adminService
          .geteditRoles(this.id)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (res) => {
              this.user = res?.role;
              this.permissionListlen = res.permissionLen;
              if (this.user?.permissions.length < this.permissionListlen) {
                this.checkAllBtn = false;
              } else {
                this.checkAllBtn = true;
              }
              this.permission = Object.entries(res.permission).map(
                ([permissionName, permissionList]: any) => {
                  permissionList = permissionList.map((e) => {
                    if (res?.permissionNames?.['includes'](e.name)) {
                      e.permission = true;
                      this.checkedRoles.push(e.id);
                    }
                    return e;
                  });
                  return { permissionName, permissionList };
                }
              );
              this.loaderService.hideLoader();
            },
            error: () => this.loaderService.hideLoader()
          });
      },
    });
  }

  roleEdit(ngForm, buttonId) {
    if (ngForm.valid) {
      this.sendingResponse[buttonId] = true;
      const data = {

        name: ngForm.value.name,
        permission: this.checkedRoles,
      };
      this.adminService
        .editRoles(this.id, data)
        .pipe(takeUntil(this.unSubscribe$))
        .subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res.success) {
              this.toastr.success(this.translate.transform(res.success));
              this.router.navigate(['/admin/manage-roles/roles-permissions']);
            }
            if (res.error) {
              this.toastr.error(this.translate.transform(res.error.message));
            }
          },
          error: () => {
             this.sendingResponse[buttonId] = false;
          },
        });
    }
  }
  checkVariante(selectedRole: any, event: any): void {
    const variante = Object.assign({}, selectedRole);
    if (event.target?.checked) {
      this.checkedRoles.push(variante.id);
      if(this.checkedRoles.length === this.permissionListlen){
        this.checkall.nativeElement.checked = true;
      }
    } else {
      this.checkedRoles = this.checkedRoles.filter((v) => v !== variante.id);
      if(this.checkedRoles.length !== this.permissionListlen){
        this.checkall.nativeElement.checked = false;
      }
    }
  }
  checkAll() {
    const userperLen = this.checkedRoles.length;
    if (userperLen < this.permissionListlen) {
      // add Check to All
      this.permission = this.permission.map((permissionList: any) => {
        permissionList.permissionList = permissionList.permissionList.map(
          (e) => {
            e.permission = true;
            this.checkedRoles.push(e.id);
            return e;
          }
        );
        return permissionList;
      });
    } else {
      // remove Check to All
      this.permission = this.permission.map((permissionList: any) => {
        permissionList.permissionList = permissionList.permissionList.map(
          (e) => {
            e.permission = false;
            this.checkedRoles = [];
            return e;
          }
        );
        return permissionList;
      });
    }
  }
}
