import { Component, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { UserService } from '../user/service/user.service';
import { lastValueFrom } from 'rxjs';
import { HttpStatusCode } from '@angular/common/http';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ToastrService } from 'ngx-toastr';
import { Router, RouterModule } from '@angular/router';

@Component({
    selector: 'app-restore-user',
    templateUrl: './restore-user.component.html',
    styleUrls: ['./restore-user.component.css'],
    standalone: false
})
export class RestoreUserComponent {

  isLoadingData = false;
  searchText: string = '';
  userEmailId = localStorage.getItem('email');

  deletedUsersDataSource: MatTableDataSource<any>;
  displayedColumns: string[] = ['id', 'userId', 'userName', 'mobileNumber', 'organisationId','actions'];

  constructor(private userService: UserService, private toastrService: ToastrService, private router:Router) {
    this.deletedUsersDataSource = new MatTableDataSource<any>([]);
  }

  async ngOnInit() {
     await this.getLoggedInUserDetails();
    if(this.hasIdrbtAdminRole()){
    await this.fetchDeletedUsers();
    }else{
      this.navigateToSessionTimeout()
    }
  }

  maxDataCount:number=0

  deletedUsers: any[] = [];
   @ViewChild(MatPaginator) paginator!: MatPaginator;
      @ViewChild(MatSort) sort!: MatSort;
 async fetchDeletedUsers() {
  this.isLoadingData = true;

  try {
    const response = await lastValueFrom(this.userService.getAllDeletedUsers());

    if (response.status === HttpStatusCode.Ok && response.body) {
      this.deletedUsers = response.body;
      this.deletedUsersDataSource.data = this.deletedUsers;
      setTimeout(() => {
              this.deletedUsersDataSource.sort = this.sort;
              this.deletedUsersDataSource.paginator = this.paginator;
            }, 0);
    } else {
      this.deletedUsers = [];
      this.deletedUsersDataSource.data = [];
    }

  } catch (error) {
    console.error('Error fetching deleted users:', error);
  } finally {
    this.isLoadingData = false;
  }
}


  async restoreUser(user: any) {
    const confirmed = window.confirm(`Are you sure you want to restore user '${user.userName}'?`);
    if (!confirmed) {
      return;
    }
    try{
      const response = await lastValueFrom(this.userService.getRestoredUser(user.rgntUserAuditId));
      if (response.status === HttpStatusCode.Ok) {
        if(response.body == true){
          this.toastrService.success('User restored successfully');
        await this.fetchDeletedUsers();
        }else{
          this.toastrService.error('User already exists with same User Id. Need not be restored.');
        }
      } 
    }catch(error){
      console.log('exe')
    }
  }

   applyFilter() {
    const filterValue = (event.target as HTMLInputElement).value.trim().toLowerCase(); // Get the filter text
 
    this.deletedUsersDataSource.filterPredicate = (data: any, filter: string) => {
   
      const displayedColumnsValues = this.displayedColumns.map(column => {
        if (column === 'requestedDate') {
          // For date columns, format the date to 'MMM d, y, h:mm a' format
          const dateValue = data[column];
          return this.formatDate(new Date(dateValue));
        // }else if(column === 'domainName'){
        //   const domainName = data.domainName?.toString().toLowerCase() || "";
        //         const bankName = data.bankName?.toString().toLowerCase() || "";
        //         // //console.log(domainName+bankName)
        //         return bankName+domainName; // Combine for filtering
        // 
        } 
        else {
          // For non-date columns, return the column value
          return data[column];
        }
      });
 
      // Perform a case-insensitive search across the columns
      return displayedColumnsValues.some(value =>
        value?.toString().toLowerCase().includes(filter)
      );
    };
 
    // Apply the filter value to the data source
    this.deletedUsersDataSource.filter = filterValue;
 
    // Reset paginator to the first page after filtering
    if (this.deletedUsersDataSource.paginator) {
      this.deletedUsersDataSource.paginator.firstPage();
    }
  }

   formatDate(date: Date): string {
    const options: Intl.DateTimeFormatOptions = {
      month: 'short',  // 'Jan', 'Feb', etc.
      day: 'numeric',  // '30', '1', etc.
      year: 'numeric', // '2025', '2026', etc.
      hour: 'numeric', // '3', '12', etc.
      minute: 'numeric', // '46', '30', etc.
      hour12: true, // AM/PM format
    };
  
    return date.toLocaleString('en-US', options); // Format as 'Jan 30, 2025, 3:46 PM'
  }
  
  user:any
    async getLoggedInUserDetails(){
      try{
        const response = await lastValueFrom(this.userService.getRgtrUserByEmailId(this.userEmailId))
        this.user= response.body;
        console.log(this.user.userRoles[0].roleName)
      }catch(error){
          if(error.status==HttpStatusCode.Unauthorized){
            this.navigateToSessionTimeout();
          }
      }
      
    }
    hasIdrbtAdminRole(): boolean {
      
      // 1. Check for null/undefined user or userRoles array for safety
      console.log(this.user )
      
      if (!this.user || !this.user.userRoles || this.user.userRoles.length === 0) {
          return false;
      }
  
      // 2. Use .some() to check if AT LEAST ONE element satisfies the condition
      return this.user.userRoles.some(role => {
          
          // Ensure roleName exists and is a string, then check for the substring
          const roleName = role.roleName;
          // console.log(typeof roleName)
          // return true
          if (typeof roleName === 'string') {
              // Convert to uppercase for case-insensitive check (good practice)
              return roleName.toUpperCase().includes('IDRBTADMIN');
          }
          
          return false;
      });
  }

  navigateToSessionTimeout(){
    this.router.navigateByUrl("session-timeout");
  }

}
