import { Component, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { BehaviorSubject, Observable, combineLatest, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Role } from './role';
import { RoleService } from './role.service';
import { NgbdSortableHeader } from './sortable.directive';
import { AddRoleComponent } from './add-role/add-role.component';
import { UtilityService } from 'src/app/shared/service/utility.service';
import { BaseService } from 'src/app/shared/service/base.service';
import { ToastService } from 'src/app/toast/toast-service';
import { RolePropertiesComponent } from './role-properties/role-properties.component';

@Component({
  selector: 'app-rolelist',
  templateUrl: './rolelist.component.html',
  styleUrls: ['./rolelist.component.scss'],
  providers: [RoleService, DecimalPipe]
})

export class RolelistComponent implements OnInit {
  @ViewChild(AddRoleComponent, { static: true }) addRoleComponent: AddRoleComponent;
  @ViewChild(RolePropertiesComponent, { static: true }) rolePropertiesComponent: RolePropertiesComponent;

  private rolesSubject = new BehaviorSubject<Role[]>([]);
  roles$ = this.rolesSubject.asObservable();
  searchTerm$ = new BehaviorSubject<string>('');
  filteredRoles$: Observable<Role[]>;
  total$: Observable<number>;

  tenants:any;


  @ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;

  constructor(public service: RoleService, private utilityService: UtilityService, public baseService: BaseService
    , private toastService : ToastService,
  ) {
    this.total$ = this.roles$.pipe(map(roles => roles.length));
  }

  ngOnInit() {
    this.getAllRole();
    this.filteredRoles$ = combineLatest([this.roles$, this.searchTerm$]).pipe(
      map(([roles, searchTerm]) => 
        roles.filter(role => role.name.toLowerCase().includes(searchTerm.toLowerCase()))
      )
      
    );

    this.addRoleComponent.roleAdded.subscribe(() => {
      this.getAllRole();
    });
    this.rolePropertiesComponent.roleAdded.subscribe(() => {
      this.getAllRole();
    });

    this.service.tenant$.subscribe(data => {
      this.tenants = data;
      console.log(this.tenants);
      
    });
  }

  getTenantName(roleId: string): string {
    const tenant = this.tenants.find(tenant => 
      tenant.tenantRole.some(role => role.roleId === roleId)
    );
    return tenant ? tenant.name : 'Tenant not found';
  }


  getAllRole() {
    this.baseService.getData('access/roles').pipe(
      map((data: any) => {
        console.log(data);
        
        return data.map((item: any) => ({
          id: item.id,
          name: item.role,
          permission:item.permissions
        }));
      }),
      catchError(err => {
        console.log(err);
        return of([]);
      })
    ).subscribe(
      (roles: Role[]) => {
        this.rolesSubject.next(roles);
      }
    );
  }

  DeleteRole(role: Role) {
    console.log(role);
    
    this.baseService.deleteData(`access/roles/${role.name}`).subscribe(
      (response: any) => {
        if (response) {
          console.log('Role deleted successfully');
          this.getAllRole();
          this.toastService.show('Role Deleted successfully!', { classname: 'bg-success text-light', delay: 3000 });
        }
      },
      (err) => {
        console.log('Full error object:', err);
        console.log('Error status:', err.status);
        console.log('Error message:', err.message);
        this.toastService.show('Role deleted unsuccessfully!', { classname: 'bg-error text-light', delay: 3000 });
      }
    );
  }

  hasPermission(permissions: string): boolean {
    return this.utilityService.hasPermission(permissions);
  }

  trackByFn(index: number, item: Role) {
    return item.id;
  }

  openAddRoleModal() {
    this.addRoleComponent.openModal();
  }

  openRolePropertiesModel(role:any){
    console.log(role);
    this.rolePropertiesComponent.role = role; 
    this.rolePropertiesComponent.openModal();
  }

  onSearchTermChange(searchTerm: string) {
    this.searchTerm$.next(searchTerm);
  }
}
