import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnInit,ChangeDetectorRef,NgZone } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { NavigationEnd, Router } from '@angular/router';
import { tap } from 'rxjs/operators';
import { Tab } from 'src/app/models/tab';
import { ProjectsStore } from 'src/app/stores/projects.store';
import data from 'src/assets/data/layout.json';
import { StorageService } from 'src/app/core/services/storage.service';
import { filter } from 'rxjs/operators';
import { getAllElements } from 'src/app/custom/common'
import { HttpClientService } from 'src/app/core/services/http-client.service';




@Component({
  selector: 'app-projects',
  templateUrl: './projects.page.html',
  styleUrls: ['./projects.page.scss'],
})
export class ProjectsPageComponent implements OnInit {
  public layoutSubmenuList = [];
  public current_label = '';
  public moduleName =    ""
  public label =  ''  ;
  public domaine =  ''  
  public tabs: Tab[] =[]
  public current_tab: any = {}

  constructor(
    private projectStore: ProjectsStore,
    private router: Router,
    public dialog: MatDialog,
    public httpClientService: HttpClientService,
    public storage: StorageService,
    private cdr: ChangeDetectorRef,    
    private zone: NgZone,
    @Inject(DOCUMENT) private document: Document
  ) {     
  }

   async ngOnInit() {  
    const __menus = await getAllElements('v1/menus',this.httpClientService);
    this.layoutSubmenuList = __menus
    
    // Gestion spéciale pour le dashboard
    const currentUrl = this.router.url;
    if (currentUrl.includes('/dashboard/')) {
      this.handleDashboardNavigation();
      return;
    }
    
    // Redirection vers les nouveaux modules si on arrive sur l'ancien système
    if (currentUrl.includes('/admin/client/') || currentUrl.includes('/admin/vente/')) {
      console.log('🔄 Redirection depuis ancien système vers nouveaux modules');
      this.router.navigate(['/admin/client/accounts']);
      return;
    }
    
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe(() => {
      this.loadMenu()
      // this.cdr.detectChanges();  
    });

    // Appeler la même fonction lors du rechargement de la page
    window.onload = () => {
      this.loadMenu()
      // this.cdr.detectChanges();  
    };
  
  }

  /**
   * Gestion spéciale de la navigation dashboard
   */
  private handleDashboardNavigation(): void {
    // Configurer les tabs pour dashboard
    this.tabs = [
      {
        label: "Général",
       icon: "dashboard",
        module: "general",
        domaine: "dashboard",
        route: "/admin/dashboard/general/list"
      },
      {
        label: "Finance", 
       icon: "account_balance",
        module: "finance",
        domaine: "dashboard",
        route: "/admin/dashboard/finance/list"
      },
      {
        label: "Projets",
       icon: "assignment",
        module: "projects", 
        domaine: "dashboard",
        route: "/admin/dashboard/projects/list"
      },
      {
        label: "Reporting",
       icon: "assessment",
        module: "reporting",
        domaine: "dashboard", 
        route: "/admin/dashboard/reporting/list"
      }
    ];
    
    this.domaine = "dashboard";
    this.label = "Dashboard";
    
    // Détecter le module actuel depuis l'URL
    const currentUrl = this.router.url;
    if (currentUrl.includes('/general/')) {
      this.moduleName = "general";
    } else if (currentUrl.includes('/finance/')) {
      this.moduleName = "finance";
    } else if (currentUrl.includes('/projects/')) {
      this.moduleName = "projects";
    } else if (currentUrl.includes('/reporting/')) {
      this.moduleName = "reporting";
    } else {
      this.moduleName = "general";
    }
    
    console.log('📊 Dashboard navigation configurée:', {
      domaine: this.domaine,
      moduleName: this.moduleName,
      tabs: this.tabs.length
    });
  }
  loadMenu(){
    const dd = this.storage.getItem('__domaineDD');
    const __domainedd = dd ? JSON.parse(dd) : {}
    if(__domainedd){
      this.domaine = __domainedd.domaine;
      this.moduleName = __domainedd.modulename;
      this.label = __domainedd.label;
    }
    if(!this.domaine){
      this.tabs =  this.layoutSubmenuList[0]['submenu']
      this.moduleName = this.tabs[0]?.module ?? ""
      this.domaine = this.tabs[0]?.domaine ?? ""
      let dommaineDD = {"modulename":this.moduleName,"domaine":this.domaine,'label':this.label}
      this.storage.setItem('__domaineDD',JSON.stringify(dommaineDD))
      // this.storage.setItem('__tabs',JSON.stringify(this.tabs))
    }else{
        let menuTabs =  this.layoutSubmenuList.filter((res: any) => {
          return res.name === this.domaine;
        });
        if(menuTabs.length != 0){
            this.tabs = menuTabs[0]['submenu']        
        }
    }
    if (this.current_label === '') {
      this.checkTabsCurrent(this.router.url);
    }
    // this.cdr.detectChanges();  
  }

  public clickTab(tabs: Tab) {
    this.moduleName = tabs.module!;
    this.domaine = tabs.domaine!;
    this.label = tabs.label!;

    let dommaineDD = {"modulename":this.moduleName,"domaine":this.domaine,'label':this.label};
   
    this.storage.setItem('__domaineDD',JSON.stringify(dommaineDD))
    this.storage.setItem('__currentTab',JSON.stringify(tabs))
    this.closeDialog();
    this.document.body.classList.remove('pop-element');
    this.router.navigate([`admin/${this.domaine.toLowerCase()}/${this.moduleName.toLowerCase()}/list/all`]);
  }

  public closeDialog() {
    this.dialog.closeAll();
  }

  public checkTabsCurrent(url: string) {
    const response = this.tabs.filter((res) => {
      return url.toLowerCase().includes(res.route.toLowerCase()) ;
    });
    this.current_label =
      response && response.length > 0 ? response[0].label : this.moduleName;
  }
}
