import { ChangeDetectorRef, Component, input, OnInit, AfterViewInit, inject, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HttpResponse } from '@angular/common/http';
import { map } from 'rxjs';

import SharedModule from 'app/shared/shared.module';
import { DurationPipe, FormatMediumDatetimePipe, FormatMediumDatePipe } from 'app/shared/date';
import { IDashboardComponent } from '../dashboard-component.model';
import { DashboardComponentService } from '../service/dashboard-component.service';
import { IDashboardComponentDetail } from '../dashboard-component-detail.model';
import { IOrganization } from 'app/entities/organization/organization.model';
import { DashboardComponentChart } from 'app/entities/dashboard-component/factory/widgets/dashboard-component-chart.component';
import { DashboardComponentFactoryService } from '../factory/dashboard-component-factory.service';

@Component({
  standalone: true,
  selector: 'jhi-dashboard-component-preview',
  templateUrl: './dashboard-component-preview.component.html',
  imports: [SharedModule, RouterModule, DurationPipe, FormatMediumDatetimePipe, FormatMediumDatePipe, DashboardComponentChart],
})
export class DashboardComponentPreviewComponent implements OnInit, AfterViewInit  {
  @ViewChild('dashboardContainer', { read: ViewContainerRef }) container!: ViewContainerRef;
  
  dashboardComponent = input<IDashboardComponent | null>(null);
  currentTab: string = 'details'; // default tab

  protected dashboardComponentService = inject(DashboardComponentService);
  
  constructor(
    private dashboardComponentFactory: DashboardComponentFactoryService,
    private cdRef: ChangeDetectorRef // Inject ChangeDetectorRef
  ) {}
  
  ngOnInit(): void {
    
  }
  
  ngAfterViewInit() {
    this.loadDashboard();
  }
  
  setTab(tabId: string): void {
    this.currentTab = tabId;
  }
  
  previousState(): void {
    window.history.back();
  }
  
  loadDashboard() {
    const _dashboardComponent: IDashboardComponent | null = this.dashboardComponent();
    if (_dashboardComponent?.type) {      
      const data = { dashboardComponent: _dashboardComponent };
      this.container.clear();
      this.dashboardComponentFactory.createComponent(_dashboardComponent?.type, this.container, data);
      
      // **Force Angular to detect changes**
      this.cdRef.detectChanges();
    }
  }
}
