import { Component, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core';
import { Observable } from 'rxjs';
import { User } from './user';
import { UserService } from './user.service';
import { NgbdSortableHeader, SortEvent } from './sortable.directive';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { AddUserComponent } from './add-user/add-user.component';
import { UserPropertiesComponent } from './user-properties/user-properties.component';
import { UtilityService } from 'src/app/shared/service/utility.service';
import { BaseService } from 'src/app/shared/service/base.service';
import { RoleService } from '../rolelist/role.service';
import { StorageService } from 'src/app/shared/service/storage.service';
import { ToastService } from 'src/app/toast/toast-service';

@Component({
  selector: 'app-userlist',
  templateUrl: './userlist.component.html',
  styleUrls: ['./userlist.component.scss'],
  providers: [UserService]
})
export class UserlistComponent implements OnInit {
  @ViewChild(AddUserComponent, { static: true }) addUserComponent: AddUserComponent;
  @ViewChild(UserPropertiesComponent, { static: true }) userPropertiesComponent: UserPropertiesComponent;

  users$: Observable<User[]>;
  total$: Observable<number>;
  tenants:any
  userLimit:number=0;
  currentUserCount: number = 0; // Store the current number of users


  @ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;

  constructor(
    public service: UserService,
    private utilityService: UtilityService,
    public baseService: BaseService,
    private modalService: NgbModal,
    public roleService:RoleService,
    private storrage:StorageService,
    public toastService: ToastService,
  ) {
    this.users$ = service.users$;
    this.total$ = service.total$;
  }

  ngOnInit() {
    this.getUserLimit();

    // Subscribe to users$ to track user count once
    this.users$.subscribe(users => {
      this.currentUserCount = users.length; // Update the current user count
    });

    this.addUserComponent.UserAdded.subscribe(() => {
      this.service.fetchUsers(); // Refresh the user list when a user is added
    });
    this.userPropertiesComponent.userUpdated.subscribe(() => {
      this.service.fetchUsers(); // Refresh the user list when a user is added
    });
    this.roleService.tenant$.subscribe(data => {
      this.tenants = data;
      console.log(this.tenants);
    });
  }

  getUserLimit(){
    const userid = this.storrage.getItem('user');

    this.baseService.getData(`tenants/getbyuserid/${userid}`).subscribe(
      (data: any) => {
        const tenantuuid = data.data[0].tenantUUID;

        const formData = new URLSearchParams();
        formData.append('tenantId', tenantuuid);
        formData.append('attribute', 'number_of_users');
  
        this.baseService.postData('subscriptions/validatePlan',formData).subscribe(
          (data: any) => {
            if (data) {
            console.log(data);       
            this.userLimit= Number(data.data)     
          }
          },
          (err) => {
            console.log(err);
          }
          );
      },
      error => {
        console.error('Request failed', error);
      }
    );
  }

  getTenantName(userid: any): string {    
    const tenant = this.tenants.find(tenant => 
      tenant.tenantUsers.some(role => role.userId ===  String(userid))
    );
    return tenant ? tenant.name : 'Tenant not found';
  }

  openAddUserModal() {
     // Check user limit directly without subscribing again
     if (this.userLimit <= this.currentUserCount) {
      this.toastService.show('Your subscription limit has been exceeded. Please upgrade to a new subscription to add more users.', { classname: 'bg-error text-light', delay: 3000 });
      return; // Prevent modal from opening
    }

    // Open the modal if user limit has not been exceeded
    this.addUserComponent.openModal();
  }

  formatDate(dateString: string): string {
    const date = new Date(dateString);
    const day = ('0' + date.getDate()).slice(-2);
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const year = date.getFullYear();
    return `${day}-${month}-${year}`;
  }

  openUserProperties(user: any) {
    this.baseService.getData(`user/getUsrByHandle/${user.username}`).subscribe(
      (data: any) => {
        if (data) {
          this.userPropertiesComponent.user = data.user;
          this.userPropertiesComponent.openModal();
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  hasPermission(permissions: string): boolean {
    return this.utilityService.hasPermission(permissions);
  }

  deleteUser(user:any){
    this.baseService.deleteData(`user/${user.id}`).subscribe(
      (response: any) => {
        if (response) {
          console.log('Role deleted successfully');
          this.service.fetchUsers();
        }
      },
      (err) => {
        console.log('Full error object:', err);
        console.log('Error status:', err.status);
        console.log('Error message:', err.message);
      }
    );
  }
}

