import { Component, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { UserService } from '../user/service/user.service';
import { ToastrService } from 'ngx-toastr';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { lastValueFrom } from 'rxjs';
import { HttpStatusCode } from '@angular/common/http';
import { Router } from '@angular/router';

@Component({
    selector: 'app-orphan-users-data',
    templateUrl: './orphan-users-data.component.html',
    styleUrls: ['./orphan-users-data.component.css'],
    standalone: false
})
export class OrphanUsersDataComponent {

  isLoadingData = false;
  userEmailId = localStorage.getItem('email');
  orphanUsersDataSource: MatTableDataSource<any>;
  displayedColumns: string[] = ['id', 'userId', 'createdDateTime', 'userName', 'mobileNumber', 'organisationId', 'actions'];

  constructor(private userService: UserService, private toastrService: ToastrService,
    private router: Router
  ) {
    this.orphanUsersDataSource = new MatTableDataSource<any>([]);
  }

   searchText: string = '';

  async ngOnInit() {
    await this.getLoggedInUserDetails();
    if(this.hasIdrbtAdminRole()){
         await this.fetchOrphanUsers();
    }else{
      this.navigateToSessionTimeout()
    }
   
  }

  maxDataCount: number = 0

  orphanUsers: any[] = [];
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  async fetchOrphanUsers() {
    this.isLoadingData = true;

    try {
      const response = await lastValueFrom(this.userService.getAllOrphanUsers());

      console.log('Orphan Users Response:', response);

      if (response.status === HttpStatusCode.Ok && response.body) {
        this.orphanUsers = response.body;
        this.orphanUsersDataSource.data = this.orphanUsers;
        setTimeout(() => {
          this.orphanUsersDataSource.sort = this.sort;
          this.orphanUsersDataSource.paginator = this.paginator;
        }, 0);
      } else {
        this.orphanUsers = [];
        this.orphanUsersDataSource.data = [];
      }

    } catch (error) {
      if (error.status === HttpStatusCode.Unauthorized) {
        this.router.navigateByUrl('session-timeout');
      } else {
        console.error(error);
      }
    } finally {
      this.isLoadingData = false;
    }
  }


  async deleteOrphanUser(user: any) {
    const confirmed = window.confirm(
      `Are you sure you want to delete this orphan user '${user.userName}'?\n\n⚠️ This action cannot be undone.`
    );


    if (!confirmed) {
      this.toastrService.info('Orphan User deletion cancelled');
      return;
    }

    try {
      const response = await lastValueFrom(this.userService.deleteOrphanUser(user.userId));

      if (response.status === HttpStatusCode.Ok) {
        this.toastrService.success('Orphan user deleted successfully');
        await this.fetchOrphanUsers();
      } else {
        this.toastrService.error('Cannot delete this user right now. please try again later.');
      }
    } catch (error) {
      console.error('Error deleting orphan user:', error);
      this.toastrService.error('Cannot delete this user right now. please try again later.');
    }
  }

  applyFilter() {
    const filterValue = (event.target as HTMLInputElement).value.trim().toLowerCase(); // Get the filter text
 
    this.orphanUsersDataSource.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.orphanUsersDataSource.filter = filterValue;
 
    // Reset paginator to the first page after filtering
    if (this.orphanUsersDataSource.paginator) {
      this.orphanUsersDataSource.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")
    }
    

}
