import { Component, OnInit, ViewChild, ChangeDetectorRef,  ElementRef,EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { User } from '../model/user.model';
import { MainHeaderService } from './service/main-header.service';
import { NotificationComponent } from '../notification/notification.component';
import { NotificationService } from '../notification/service/notification.service';
import { interval, lastValueFrom, Subscription } from 'rxjs';
import { environment } from '../environments/environment';
import { ToastrService } from 'ngx-toastr';
import { UserService } from '../user/service/user.service';
import { HttpStatusCode } from '@angular/common/http';
import { DomainService } from '../rgnt-domain/service/domain.service';

@Component({
    selector: 'app-main-header',
    templateUrl: './main-header.component.html',
    styleUrls: ['./main-header.component.css'],
    standalone: false
})
export class MainHeaderComponent implements OnInit{

  user: User | null = null;  
  loading: boolean = true;    
  error: string = '';
  isNotificationVisible = false;
  notificationModalId = 'notificationModal';
  notificationCount: number = 0; 
  notificationList: any[] = []; 
  userMailId = localStorage.getItem('email');
  notificationError: string | null = null;
  private notificationSubscription: Subscription;
  organisationId: string | null = null;
submissionDate: string | null = null;
creationDate: string | null = null;
currentDateTime: string = '';

  @ViewChild('fileInput') fileInput: any;
  
  @ViewChild(NotificationComponent) notificationComponent: NotificationComponent;
  constructor(private router: Router, private mainHeaderService: MainHeaderService,private notificationService: NotificationService, 
    private cdr: ChangeDetectorRef, private toastr : ToastrService,private domainService:DomainService,
  private userService: UserService){
      window.addEventListener('storage', (event: StorageEvent) => {
        if (event.key === 'logoutEvent' && event.newValue === 'true') {
          this.logoutFromOtherTabs();
        }
      });
    }
    // private logoutFromOtherTabs(): void {
    //   localStorage.clear();
    //   sessionStorage.clear();
    //   this.router.navigateByUrl('/login');
    // }

//     private logoutFromOtherTabs(): void {

//   const organisationId = localStorage.getItem('organisationId');
//   const organisationDetailsId = localStorage.getItem('organisationDetailsId');

//   localStorage.clear();
//   sessionStorage.clear();

//   if (organisationId) {
//     localStorage.setItem('organisationId', organisationId);
//   }

//   if (organisationDetailsId) {
//     localStorage.setItem('organisationDetailsId', organisationDetailsId);
//   }

//   this.router.navigateByUrl('/login');
// }

private logoutFromOtherTabs(): void {

  const organisationId = localStorage.getItem('organisationId');
  const organisationDetailsId = localStorage.getItem('organisationDetailsId');
  const submissionDate = localStorage.getItem('submissionDate');
  const creationDate = localStorage.getItem('creationDate');

  localStorage.clear();
  sessionStorage.clear();

  if (organisationId) {
    localStorage.setItem('organisationId', organisationId);
  }

  if (organisationDetailsId) {
    localStorage.setItem('organisationDetailsId', organisationDetailsId);
  }

  if (submissionDate) {
    localStorage.setItem('submissionDate', submissionDate);
  }

  if (creationDate) {
    localStorage.setItem('creationDate', creationDate);
  }

  this.router.navigateByUrl('/login');
}

  pageType:string
  ngOnInit(): void {

    this.pageType=localStorage.getItem('pageType');
   //console.log(this.pageType)
     this.getUserDetails(); 
     this.setupNotificationPolling();
     this.notificationComponent?.loadNotifications();
    const storedProfilePictureUrl = localStorage.getItem('profilePictureUrl');
    if (storedProfilePictureUrl) {
        if (this.user) {
            this.user.profilePictureUrl = storedProfilePictureUrl;
        }
    }
    this.loadNotifications();

  const organisationId = localStorage.getItem('organisationId');
  const submissionDate = localStorage.getItem('submissionDate');
  const creationDate = localStorage.getItem('creationDate');

  if (organisationId) {
    this.organisationId = organisationId;
  }

  if (submissionDate) {
    this.submissionDate = submissionDate;
  }

  if (creationDate) {
    this.creationDate = creationDate;
  }


  this.updateCurrentDateTime();

setInterval(() => {
  this.updateCurrentDateTime();
}, 1000);

   }

   
   ngOnDestroy(): void {
    if (this.notificationSubscription) {
      this.notificationSubscription.unsubscribe();
    }
  }


   loadNotifications(): void {
    if (this.userMailId) {
      this.notificationService.getNotifications(this.userMailId).subscribe(
        (notifications: any[]) => {
          this.notificationList = notifications; 
          this.notificationCount = notifications.filter(n => n.status === 'Unread').length; 
          this.cdr.detectChanges(); 
          this.notificationError = null;
          //console.log('Notifications loaded:', this.notificationList);
        },
        (error) => {
          this.notificationError = 'Error fetching notifications: ' + error.message;
          //console.error('Error fetching notifications:', error);
        }
      );
    }
  }

  setupNotificationPolling(): void {
    this.notificationSubscription = interval(5000).subscribe(() => {
      this.loadNotifications();
    });
  }

    cancelButton(){
    setTimeout(() => {
      
    }, 200);
    // window.location.reload();
  }
  
  toggleNotification(): void {
    this.isNotificationVisible = !this.isNotificationVisible;
    if (this.isNotificationVisible) {
      //console.log('Notification Modal opened, marking notifications as read...');
      
      // Ensure userMailId exists before calling the service
      if (this.userMailId) {
        this.markNotificationsAsRead(this.userMailId); // Call the function to mark as read
      } else {
       //console.error('User email is not available.');
      }
    }
  }
  markNotificationsAsRead(emailId: string): void {
   //console.log('Calling markAllAsRead service for emailId:', emailId);
    this.notificationService.markAllAsRead(emailId).subscribe(
      (response) => {
       //console.log('All notifications marked as read:', response);
        this.notificationCount = 0; // Reset the notification count
        // Update notification status locally
        this.notificationList.forEach(notification => {
          notification.status = 'Read'; // Update status locally
        });
      },
      (error) => {
        //console.error('Error marking notifications as read:', error);
      }
    );
  }
  
  onNotificationToggle(value: boolean): void {
    this.isNotificationVisible = value; 
  }

  role: string = localStorage.getItem('userRole');
  // async logout() {
  //   document.getElementById("closeProfilePannel").click();
  //   localStorage.setItem('logoutEvent', 'true'); // Trigger cross-tab logout
  //   localStorage.clear(); // Clear all localStorage
  //    sessionStorage.clear();
  //   //await this.getUserByEmailId(this.user.userId);
  //   //this.currentLogginInUser = false;
  //   //await this.updateUser(this.currentLogginInUser)
  
  //   if(this.role === 'IDRBTADMIN'){
  //     this.router.navigateByUrl('/rgtr-login').then(() => {
  //       this.toastr.success('Hope you had a great experience', 'Logged out successfully');
  //       localStorage.removeItem('logoutEvent'); // Clear the event flag
  //     });
  //   }else{
  //     this.router.navigateByUrl('/login').then(() => {
  //       this.toastr.success('Hope you had a great experience', 'Logged out successfully');
  //       localStorage.removeItem('logoutEvent'); // Clear the event flag
  //     });
  //   }
    
  //   //update isLoggedIn to false
  //   //this.updateUser
  // }
//   async logout() {

//   document.getElementById("closeProfilePannel").click();

//   // 🔥 STORE REQUIRED DATA BEFORE CLEAR
//   const organisationId = localStorage.getItem('organisationId');
//   const organisationDetailsId = localStorage.getItem('organisationDetailsId');

//   localStorage.setItem('logoutEvent', 'true');

//   localStorage.clear();
//   sessionStorage.clear();

//   // 🔥 RESTORE AFTER CLEAR
//   if (organisationId) {
//     localStorage.setItem('organisationId', organisationId);
//   }

//   if (organisationDetailsId) {
//     localStorage.setItem('organisationDetailsId', organisationDetailsId);
//   }

//   if (this.role === 'IDRBTADMIN') {
//     this.router.navigateByUrl('/rgtr-login').then(() => {
//       this.toastr.success('Hope you had a great experience', 'Logged out successfully');
//       localStorage.removeItem('logoutEvent');
//     });
//   } else {
//     this.router.navigateByUrl('/login').then(() => {
//       this.toastr.success('Hope you had a great experience', 'Logged out successfully');
//       localStorage.removeItem('logoutEvent');
//     });
//   }
// }
async logout() {

  document.getElementById("closeProfilePannel").click();

  // 🔥 STORE REQUIRED DATA BEFORE CLEAR
  const organisationId = localStorage.getItem('organisationId');
  const organisationDetailsId = localStorage.getItem('organisationDetailsId');
  const submissionDate = localStorage.getItem('submissionDate');
  const creationDate = localStorage.getItem('creationDate');

  localStorage.setItem('logoutEvent', 'true');

  localStorage.clear();
  sessionStorage.clear();

  // 🔥 RESTORE AFTER CLEAR
  if (organisationId) {
    localStorage.setItem('organisationId', organisationId);
  }

  if (organisationDetailsId) {
    localStorage.setItem('organisationDetailsId', organisationDetailsId);
  }

  if (submissionDate) {
    localStorage.setItem('submissionDate', submissionDate);
  }

  if (creationDate) {
    localStorage.setItem('creationDate', creationDate);
  }

  if (this.role === 'IDRBTADMIN') {
    this.router.navigateByUrl('/rgtr-login').then(() => {
      this.toastr.success('Hope you had a great experience', 'Logged out successfully');
      localStorage.removeItem('logoutEvent');
    });
  } else {
    this.router.navigateByUrl('/login').then(() => {
      this.toastr.success('Hope you had a great experience', 'Logged out successfully');
      localStorage.removeItem('logoutEvent');
    });
  }
}
  // notifications(){
  //   if (this.notificationComponent) {
  //     this.notificationComponent.showModal();
  //   }
  // }
  getUserRoles(): string {
     if (!this.user?.userRoles || this.user.userRoles.length === 0) {
      return '';
  }

  const modifiedRoles = this.user.userRoles.map(role => {
      if (role.roleName === "Billing Officer") {
          return { ...role, roleName: "Financial Officer" }; // Replace "Billing Officer"
      }
      return role; // Keep other roles as they are
  });

  return modifiedRoles.length > 1
      ? modifiedRoles.map(role => role.roleName).join(', ')
      : modifiedRoles[0].roleName;
}
  navigateToChangepassword(){
    document.getElementById("closeProfilePannel").click();
    this.router.navigateByUrl("/change-password")
  }

  onImageLoad() {
   //console.log("Profile image successfully loaded into the DOM.");
  }  

  getUserDetails() {  
    if(this.pageType=='rgtrUser'){
      this.mainHeaderService.getRgtrUserDetailsById(localStorage.getItem('email')).subscribe(
        response => {
         //console.log('User data received from API:', response);
          this.user=response

         
          this.loading = false; 
        },
        (error) => {
          this.error = 'Error fetching user details.';
          this.loading = false; 
          //console.error('Error fetching user details:', error);
        }
      );
    }else if(this.pageType=='user'){
      this.mainHeaderService.getUserDetailsById(localStorage.getItem('email')).subscribe(
        response => {
        //  //console.log('User data received from API:', response);
          this.user=response

         
          this.loading = false; 
        },
        (error) => {
          this.error = 'Error fetching user details.';
          this.loading = false; 
          //console.error('Error fetching user details:', error);
        }
      );
    }
     

    }

  triggerFileInput() {
    this.fileInput.nativeElement.click();
  }
maxFileSizeInMB: number = environment.maxFileSizeMB;
  onChangeFile(event: any): void {
    if (event.target.files.length > 0) {
        // const file = event.target.files[0];
        // const maxFileSize = this.maxFileSizeInMB * 1024 * 1024; 
const file = event.target.files[0];
if (!file.name.toLowerCase().endsWith('.jpg')) {
  this.toastr.error('Only JPG files are allowed');
  event.target.value = '';
  return;

}

const maxFileSize = this.maxFileSizeInMB * 1024 * 1024;

        if (file.size > maxFileSize) {
          alert(`Select a file less than  ${maxFileSize}MB`);
          event.target.value = ''; 
          return; 
        }
        const formData = new FormData();
        formData.append('file', file);
        if(this.pageType=='rgtrUser'){
          this.mainHeaderService.uploadRegistrarProfilePicture(localStorage.getItem('email')!, formData).subscribe(
            (response: Blob) => {
                this.user.profilePicture = response;  
              //  //console.log(response)
                this.user.profilePictureUrl = URL.createObjectURL(response);  
                localStorage.setItem('profilePictureUrl', this.user.profilePictureUrl);
                // window.location.reload()
              //  //console.log('Profile picture uploaded successfully');
            },
            (error) => {
              //  //console.error('Error uploading profile picture', error);
            }
        );
        }else if(this.pageType=='user'){
          this.mainHeaderService.uploadProfilePicture(localStorage.getItem('email')!, formData).subscribe(
            (response: Blob) => {
                this.user.profilePicture = response;  
              //  //console.log(response)
                this.user.profilePictureUrl = URL.createObjectURL(response);  
                localStorage.setItem('profilePictureUrl', this.user.profilePictureUrl);
                // window.location.reload()
              //  //console.log('Profile picture uploaded successfully');
            },
            (error) => {
              //  //console.error('Error uploading profile picture', error);
            }
        );
        }
        
    }
}

deleteProfilePicture(): void {
  if(this.pageType=='user'){
  if (this.user && this.user.userId) {
    this.mainHeaderService.deleteProfilePicture(this.user.userId).subscribe({
      next:(response)=>{
        this.user.profilePicture = null;
        this.user.profilePictureUrl = null;
        localStorage.removeItem('profilePictureUrl');
      //  //console.log('Profile picture deleted successfully.');
const fileInput = document.getElementById('file-input') as HTMLInputElement;
if (fileInput) {
  fileInput.value = ''; 
}
      },error:(error) => {
      //  //console.error('Error deleting profile picture:', error);
      }
    }
    )}
  }
else if(this.pageType=='rgtrUser'){
  if (this.user && this.user.userId) {
    this.mainHeaderService.deleteRegistrarProfilePicture(this.user.userId).subscribe({
      next:(response)=>{
        this.user.profilePicture = null;
        this.user.profilePictureUrl = null;
        localStorage.removeItem('profilePictureUrl');
      //  //console.log('Profile picture deleted successfully.');
const fileInput = document.getElementById('file-input') as HTMLInputElement;
if (fileInput) {
  fileInput.value = ''; 
}
      },error:(error) => {
      //  //console.error('Error deleting profile picture:', error);
      }
    }
    )} 
}
}

async updateUser(user: any){
    user.isLoggedIn = true;
    await lastValueFrom(this.userService.updateUser(user)).then(response => {
      if(response.status === HttpStatusCode.PartialContent){
      //  //console.log(user);
      }
    })
  }

  currentLogginInUser: any;
  async getUserByEmailId(emailId: string){
    await lastValueFrom(this.userService.getUserByEmailId(this.user.userId)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.currentLogginInUser = response.body;
        }
      }
    )
  }

  async deleteAccount(emailId) {
    const isSuperAdmin = this.user?.userRoles?.some(roleObject =>
      roleObject.roleName === "Super Admin"
    ) || false;
    if (isSuperAdmin) {
      if (this.user?.organisationId == 0 || this.user?.organisationId == null) {
        this.executeDeletion(emailId);
      }else{
         this.toastr.error("Account has started onboarding. Please contact registrar to delete account.");
      }
    } else {
      const hasAnyRole = (this.user?.userRoles?.length > 0) || false;

      if (!hasAnyRole) {
        if (this.user?.organisationId == 0 || this.user?.organisationId == null) {
          this.executeDeletion(emailId)
        }else{
         this.toastr.error("Account has started onboarding. Please contact registrar to delete account.");
      }
      }
    }


  }

  private async executeDeletion(emailId: string): Promise<void> {
    try {
      const confirmed = window.confirm(`Are you sure you want to delete your account ? This action cannot be undone.`);
    
    // Exit if the user clicks 'Cancel'
    if (!confirmed) {
        this.toastr.info("Account deletion cancelled")
        return; 
    }
      // Check for associated domains (onboarding status)
      const domainResponse = await lastValueFrom(this.domainService.getDomainsByUserEmail(emailId));

      if (domainResponse?.body?.length > 0) {
        this.toastr.error("Account has started onboarding. Please contact registrar to delete account.");
        return;
      }

      // Execute deletion
      const deleteResponse = await lastValueFrom(this.userService.deleteOrphanUser(emailId));

      if (deleteResponse.status === HttpStatusCode.Ok) {
        this.toastr.success("Account deleted successfully");
        document.getElementById('closeProfilePannel')?.click();

        this.router.navigateByUrl("/session-timeout");

      } else {
        this.toastr.warning(`Please try after some time`);
      }

    } catch (error) {
      
    }
  }
 isSuperAdmin(user: User | null | undefined): boolean {
  
  return user?.userRoles?.some(roleObject => roleObject.roleName === "Super Admin") || false;
}


updateCurrentDateTime() {

  const now = new Date();

  this.currentDateTime = now.toLocaleString('en-IN', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    hour12: true
  });
}


}