import { Component, OnInit, QueryList, ViewChild, ViewChildren, ChangeDetectorRef, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Tenant } from './tenant';
import { TenantService } from './tenant.service';
import { NgbdSortableHeader } from './sortable.directive';
import { AddTenantComponent } from './add-tenant/add-tenant.component';
import { UtilityService } from 'src/app/shared/service/utility.service';
import { BaseService } from 'src/app/shared/service/base.service';
import { TenantPropertiesComponent } from './tenant-properties/tenant-properties.component';
import confetti from 'canvas-confetti';


@Component({
  selector: 'app-tenantlist',
  templateUrl: './tenantlist.component.html',
  styleUrls: ['./tenantlist.component.scss'],
  providers: [TenantService]
})
export class TenantlistComponent implements OnInit, AfterViewInit {
  @ViewChild(AddTenantComponent, { static: true }) addTenantComponent: AddTenantComponent;
  @ViewChild(TenantPropertiesComponent, { static: true }) tenantPropertiesComponent: TenantPropertiesComponent;

  tenants$: Observable<Tenant[]>;
  total$: Observable<number>;

  loading = false;
  // confettiNum = 400;
  // coinNum = 30;
  // dollarNum = 50;
  // showAnimationFlag = false;

  // positions: { [key: string]: string } = {};

  @ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;

  constructor(
    public service: TenantService,
    private utilityService: UtilityService,
    public baseService: BaseService,
    private cdr: ChangeDetectorRef
  ) {
    this.tenants$ = service.device$;
    this.total$ = service.total$;
  }

  ngOnInit() {
    this.getAlltenant();
    this.addTenantComponent.tenantAdded.subscribe(() => {
      this.getAlltenant();
    });
    this.tenantPropertiesComponent.tenantAdded.subscribe(() => {
      this.getAlltenant();
    });
  }


  ngAfterViewInit() {
    // this.calculatePositions();
    // this.cdr.detectChanges(); // Trigger change detection after view initialization
  }

  // randomPosition(): string {
  //   return `${Math.random() * 100}vw`; // Random position within the viewport width
  // }

  // calculatePositions() {
  //   for (let i = 0; i < this.confettiNum; i++) {
  //     this.positions[`confetti-${i}`] = this.randomPosition();
  //   }
  //   for (let i = 0; i < this.coinNum; i++) {
  //     this.positions[`coin-${i}`] = this.randomPosition();
  //   }
  //   for (let i = 0; i < this.dollarNum; i++) {
  //     this.positions[`dollar-${i}`] = this.randomPosition();
  //   }
  // }

  // showAnimation() {
  //   console.log("inside show");
  //   this.showAnimationFlag = true;
  //   setTimeout(() => {
  //     this.showAnimationFlag = false;
  //     this.cdr.detectChanges(); // Trigger change detection after hiding animation
  //   }, 10000); // Adjust the duration as needed
  // }

  showConfetti(): void {
    confetti();
  }

  getAlltenant() {
    this.baseService.getData('tenants/getAllTenants').subscribe(
      (data: any) => {
        if (data && data.data) {
          this.service.setTenants(data.data); // Use a method to set tenants in service
        }
      },
      (err) => {
        console.error('Error fetching tenants:', err);
      }
    );
  }

  openAddTenantModal() {
    if (this.addTenantComponent) {
      this.addTenantComponent.openModal();
    } else {
      console.error('AddTenantComponent is not initialized');
    }
  }

  openTenantPropertiesModal(data: Tenant) {
    if (this.tenantPropertiesComponent) {
      this.tenantPropertiesComponent.tenant = data; 
      this.tenantPropertiesComponent.openModal();
    } else {
      console.error('TenantPropertiesComponent is not initialized');
    }
  }

  DeleteRole(tenant: Tenant) {
    this.baseService.deleteData(`tenants/${tenant.name}`).subscribe(
      (response: any) => {
        if (response) {
          console.log('Tenant deleted successfully');
          this.getAlltenant();
        }
      },
      (err) => {
        console.error('Error deleting tenant:', err);
        // this.utilityService.showError('Failed to delete tenant.'); // Example of error feedback
      }
    );
  }

  hasPermission(permissions: string): boolean {
    return this.utilityService.hasPermission(permissions);
  }

  trackByIndex(index: number, obj: any): any {
    return index;
  }
}
