import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import * as $ from 'jquery';
import { UserService } from '../user/service/user.service';
import { User } from '../model/user.model';
import { OrganisationDetailsService } from '../organisation-details/service/organisation-details.service';
import { lastValueFrom } from 'rxjs';
import { HttpStatusCode } from '@angular/common/http';

@Component({
    selector: 'app-side-menu',
    templateUrl: './side-menu.component.html',
    styleUrls: ['./side-menu.component.css'],
    standalone: false
})
export class SideMenuComponent implements OnInit {

  isBoxVisible: boolean = false;
  orgStatus: string = '';
  boxContent: string = 'Settings Box Opened';
  role: any = localStorage.getItem('userRole');

  domainRoute: string = '';

 constructor(
  private router: Router,
  private userService: UserService,
  private organisationService: OrganisationDetailsService
) {
  this.domainRoute = this.role === 'IDRBTADMIN'
    ? '/rgtr-domains'
    : '/rgnt-domains';
}

  ngOnInit(): void {
    if (this.role != 'IDRBTADMIN') {
      this.getLoggedInUserDetails();
    }
  //  this.getOrganisationDetailsById(organisationId)
  }

  isNotOnlyBillingOfficer(): boolean {
    return this.user?.userRoles
      ? !(this.user.userRoles.length === 1 && this.user.userRoles[0].roleName === 'Billing Officer')
      : true;
  }

  isNotOnlyTechnicalOfficer(): boolean {
    return this.user?.userRoles
      ? !(this.user.userRoles.length === 1 && this.user.userRoles[0].roleName === 'Technical Officer')
      : true;
  }

  isSuperAdmin: boolean = false;

  hasSuperAdminRole(): boolean {
    return this.user?.userRoles
      ? this.user.userRoles.some(role =>
          role.roleName === 'Super Admin' ||
          role.roleName === 'Administrative Officer')
      : false;
  }

  user: User;

  // getLoggedInUserDetails() {
  //   this.userService.getUserByEmailId(localStorage.getItem('email')).subscribe({
  //     next: (response) => {
  //       this.user = response.body;
  //       this.isSuperAdmin = this.hasSuperAdminRole();
  //       this.role = this.user.userRoles.map(role => role.roleName);
  //     }
  //   });
  // }
getLoggedInUserDetails() {
  this.userService.getUserByEmailId(localStorage.getItem('email')).subscribe({
    next: (response) => {
      this.user = response.body;
      this.isSuperAdmin = this.hasSuperAdminRole();
      this.role = this.user.userRoles.map(role => role.roleName);

      // 🔥 ADD THIS (IMPORTANT)
      const orgId = this.user?.organisationId;
      if (orgId) {
        this.getOrganisationDetailsById(orgId);
      }

    }
  });
}
  isSettingsOpen = false;

  usernavigation() {
    this.router.navigate(['/users']);
  }

  rolenavigation() {
    this.router.navigate(['/roles']);
  }

  // ================= SETTINGS BOX =================
  toggleBox(): void {
    console.log('[Settings Box] → ENTERING');
    this.isBoxVisible = true;

    this.toggleReportsBoxout();
    this.toggleApprovalBoxout();
  }

  toggleBoxout(): void {
    console.log('[Settings Box] → LEAVING');
    setTimeout(() => {
      this.isBoxVisible = false;
    }, 0);
  }

  // ================= REPORTS BOX =================
  isReportsBoxVisible: boolean = false;

  toggleReportsBox(): void {
    console.log('[Reports Box] → ENTERING');
    this.isReportsBoxVisible = true;

    // ✅ CLOSE ONLY OTHER BOXES
    this.toggleBoxout();
    this.toggleApprovalBoxout();

    // ❌ REMOVED THIS LINE (THIS WAS THE BUG)
    // this.toggleReportsBoxout();
  }

  toggleReportsBoxout(): void {
    console.log('[Reports Box] → LEAVING');
    setTimeout(() => {
      this.isReportsBoxVisible = false;
    }, 0);
  }

  // ================= APPROVAL BOX =================
  isApprovalBoxVisible: boolean = false;

  toggleApprovalReportsBox(): void {
    console.log('[Approval Box] → ENTER');
    this.isApprovalBoxVisible = true;

    this.toggleBoxout();
    this.toggleReportsBoxout();
  }
toggleRenewalReqsBox(): void {
  console.log('[Renewal Box] → ENTER');
  this.isApprovalBoxVisible = true;

  this.toggleBoxout();
  this.toggleReportsBoxout();
}


  toggleApprovalBoxout(): void {
    console.log('[Approval Box] → LEAVE');
    setTimeout(() => {
      this.isApprovalBoxVisible = false;
    }, 0);
  }

  // ================= ROUTE ACTIVE =================
  isRouteActive(routes: string[]): boolean {
    return routes.some(route => this.router.url.match(route));
  }

    organisationDetails: any;
async getOrganisationDetailsById(organisationId: number) {
  if (organisationId != 0) {
    await lastValueFrom(
      this.organisationService.getOrganisationDetailsByOrganisationId(organisationId)
    ).then(response => {

      if (response.status === HttpStatusCode.Ok) {

        this.organisationDetails = response.body;
        this.orgStatus = response.body.organisationApplicationStatus;

        // ✅ CALL FUNCTION HERE
        const isDisabled = this.isMenuDisabled();
      

      }

    }).catch(error => {

      if (error.status === HttpStatusCode.Unauthorized) {
        this.router.navigate(['/session-timeout']);
      }

    });
  }
}

isMenuDisabled(): boolean {

  const status = this.orgStatus?.trim().toUpperCase();

  // 🔥 if no org OR not loaded → disable
  if (!status) {
    return true;
  }

return this.isSuperAdmin &&
       status !== 'SUBMITTED' &&
       status !== 'APPROVED' &&
       status !== 'REJECTED';
}


}
