import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, NavigationEnd, Router } from "@angular/router";
import { Tab } from "src/app/models/tab";
import { EventService } from "src/app/core/services/event.service";
import { StorageService } from 'src/app/core/services/storage.service';
import { ProjectsStore } from "src/app/stores/projects.store";
import { lowerFirstLetter, getListViewElements } from "src/app/custom/common";
import { getAllElements } from "src/app/custom/common";
import { DataService } from "src/app/core/services/data.service";
import { HttpClientService } from "src/app/core/services/http-client.service";

@Component({
  selector: "app-home-projects",
  templateUrl: "./home-projects.page.html",
  styleUrls: ["./home-projects.page.scss"],
})
export class HomeProjectsPageComponent implements OnInit {
  public tabs: Tab[] = [];
  public isFirst = true;
  public moduleName: string = "";
  public domaine: string = "";
  public currentTab: any;
  public label: any;
  public menus: any = [];
  constructor(
    public storage: StorageService,
    public dataService: DataService,
    public httpClientService: HttpClientService,
    public projectStore: ProjectsStore,
    private routeur: Router,
    private event: EventService,
    private route: ActivatedRoute
  ) {}

  async ngOnInit() {
    // Note: Redirection désactivée pour permettre l'accès direct aux modules vente et client
    // const currentUrl = this.routeur.url;
    // if (currentUrl.includes('/admin/client/') || currentUrl.includes('/admin/vente/')) {
    //   console.log('🔄 Redirection depuis ancien système vers nouveaux modules');
    //   this.routeur.navigate(['/admin/client/accounts']);
    //   return;
    // }

    this.menus = await getAllElements("v1/menus", this.httpClientService);
    let name = this.menus[0].submenu[0].domaine;
    name = name[0].toUpperCase() + name.substr(1).toLowerCase();
    this.getModuleName(name);
  }

  public getModuleName(name: any) {
    let response = this.menus.filter((res: any) => {
      return res.submenu[0]?.domaine.toLowerCase() === name.toLowerCase();
    });
    const __currentTab = this.storage.getItem("__currentTab");
    let domaineDD = this.storage.getItem("__domaineDD");
    const __domaineDD = domaineDD ? JSON.parse(domaineDD) : {};

    if (__currentTab && __currentTab.length != 0) {
      this.currentTab = __currentTab;
    } else {
      this.currentTab = this.menus[0]["submenu"][0];
    }
    if (__domaineDD != undefined) {
      this.domaine = __domaineDD.domaine;
      this.moduleName = __domaineDD.modulename;
    } else {
      let submenu = response[0].submenu[0];
      this.moduleName = submenu.module; //this.currentTab.module
      this.domaine = submenu.domaine;
      this.label = submenu.label;
      this.currentTab = submenu.module; //this.currentTab.domaine
      this.storage.setItem("__currentTab", this.currentTab);
      let dd = {
        modulename: this.moduleName,
        domaine: this.domaine,
        label: this.label,
      };
      this.storage.setItem("__domaineDD", JSON.stringify(dd));
    }
    this.getSetupProject();
  }

  async getSetupProject() {
    let lvs = await getListViewElements(this.moduleName, this.dataService);
    if (lvs != undefined && lvs[this.moduleName]) {
      // Support both old format (lvs[module].data.ListeView) and new format (lvs[module].ListeView)
      const moduleData = lvs[this.moduleName];
      const listeView = moduleData.data?.ListeView || moduleData.ListeView;

      if (listeView && listeView.list && listeView.list.length > 0) {
        this.tabs = listeView.list;
        this.event.current_section$.next(listeView.list[0].name);
      } else {
        console.warn('⚠️ Aucune ListeView trouvée dans les métadonnées');
      }

      if (
        this.domaine == undefined ||
        this.domaine.length == 0 ||
        this.moduleName == undefined ||
        this.moduleName.length == 0
      ) {
        return;
      }
      let currentRoute =
        lowerFirstLetter(this.domaine) +
        "/" +
        lowerFirstLetter(this.moduleName);
      this.routeur.navigate([
        `admin/${currentRoute}/list`
      ]);
      this.isFirst = false;
    }
  }

  public sendCurrentParams(section: any) {
    console.log("mySection", section);
    this.event.current_section$.next(section);
  }
}
