import { AfterViewInit, Component, Input, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { UserService } from '../user/service/user.service';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { ContactDetailsFormService } from '../contact-details-form/service/contact-details-form.service';
import { OrganisationDetailsService } from '../organisation-details/service/organisation-details.service';
import { ContactDocumentUploadService } from '../contact-document-upload/service/contact-document-upload.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse, HttpStatusCode } from '@angular/common/http';
import * as bootstrap from 'bootstrap';
import { ContactDetailsFormComponent } from '../contact-details-form/contact-details-form.component';
import { DocumentUploadComponent } from '../document-upload/document-upload.component';
import { error } from 'jquery';
import { environment } from '../environments/environment';
import { RgtrRgntOfficerDetailsService } from '../rgtr-rgnt-officer-details/services/rgtr-rgnt-officer-details.service';
import { DomainService } from '../rgnt-domain/service/domain.service';
import { AssetService } from '../asset.service';

@Component({
    selector: 'app-rgnt-officer-details-mgmt',
    templateUrl: './rgnt-officer-details-mgmt.component.html',
    styleUrls: ['./rgnt-officer-details-mgmt.component.css'],
    standalone: false
})
export class RgntOfficerDetailsMgmtComponent implements OnInit{

  selectedOrganisation: number = 0;

  user = {
    id: 0,
    userName: '',
    userId: '',
    role: '',
    active: false,
    encryptedPassword: '',
    mobileNumber: '',
    confirmPassword: '',
    createdByEmailId:'',
    organisationId:0,
    organisationDetails: {},
    isOnboardingCompleted: false
  }


  showEmailButton: boolean = false;
  showNumberButton: boolean = false;
  isPasswordVisible: boolean = false;
  isConfirmPasswordVisible: boolean = false;

  //isToggleOn: boolean = false;

  displayedColumns: string[] = [];// Matches matColumnDef values

  usersList: any[];
  usersDataSource: MatTableDataSource<any>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  userId = localStorage.getItem('email');
  role = localStorage.getItem('userRole');
  // organisationId = localStorage.getItem('organisationId');
  organisationId:any=0;
  myForm: any;
  userRole: any;

  constructor(private userService: UserService, private router: Router,
    private toastr: ToastrService, private organisationService: OrganisationDetailsService,
    private contactDetailsService: ContactDetailsFormService,
    private contactDocumentsService: ContactDocumentUploadService,
    private rgtrRgntOfficerDetailsService: RgtrRgntOfficerDetailsService,
    private domainService: DomainService,
    private assetService: AssetService
  ) {
    this.usersDataSource = new MatTableDataSource<any>();
  }
  // ngAfterViewInit(): void {
  //   throw new Error('Method not implemented.');
  // }
    
  organisationsList: any[] = [];
  async getOrganisations(){
    await lastValueFrom(this.organisationService.getAllOrganisations()).then(
      response => {
        //console.log(this.organisationsList);
        if(response.status === HttpStatusCode.Ok){
          this.organisationsList = response.body;
          this.isLoadingData=false
        }
      }, error => {
        this.isLoadingData=false
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    )
  }

  async getUserById(id: number, contactRole: string) {
    //console.log('Role passed:', contactRole);  // Debugging line
    if (contactRole === 'Administrative Officer') {
      this.getAdminOfficerDetails(id);
      //console.log(contactRole);
    } else if (contactRole === 'Technical Officer') {
      await this.getTechnicalOfficerDetails(id);
    } else {
      await this.getBillingOfficerDetails(id);
    }
  }
  

  loggedInUser: any;
  isLoadingData:boolean=false;
  isOnboardingCompleted:boolean=false;
  async getLoggedInUserDetails(){
    this.isLoadingData=true;
    if(this.userId==null||this.userId==''){
      this.navigateToSessionTimeout()
      this.isLoadingData=false;
    }
    //console.log("enytered")
   await lastValueFrom(this.userService.getUserByEmailId(this.userId)).then(
    response => {
      if(response.status === HttpStatusCode.Ok){
        this.loggedInUser = response.body;
        // console.log( this.loggedInUser )
        const userRoles=this.loggedInUser.userRoles
        if (userRoles.some(role => role.roleName === "Super Admin")) {
          this.userRole = "Super Admin"; 
        }
        this.isOnboardingCompleted=this.loggedInUser.isOnboardingCompleted;
        this.organisationId=this.loggedInUser.organisationId;
        this.selectedOrganisationId =this.organisationId;
        //console.log("enytered")
        this.getContactOfficersDetails(parseInt(this.organisationId));
      }
    },error => {
      this.isLoadingData=false;
      if(error.status === HttpStatusCode.Unauthorized){
        this.navigateToSessionTimeout();
      }
    }
   )
  }

  @ViewChild(ContactDetailsFormComponent) contactDetailsForm: ContactDetailsFormComponent;
 resetForm() {
    if ( this.contactDetailsForm) {
      this.contactDetailsForm.resetForm();
   
    }
    this.clearAddUserData();
  }
openTheEditContactDetailsModal:boolean=false;
selectedEditOfficer:string =null;
  async ngOnInit(): Promise<void> {
    // this.selectedOrganisationId =parseInt(localStorage.getItem('organisationId'));
    //set table comumns based on role
    //if(this.role === 'IDRBTADMIN'){
      this.displayedColumns = [
        //'checkbox',
        'ids',
        'organisationName',
        'personName',
        'designation',
        'mobileNumber',
        'emailId',
        'contactRole',
        // 'verifyEmail',
        'documents',
        //'approveOrReject',
        'loginStatus',
        'isContactSentToNixi',
        // 'edit',
        'delete',
        'actions'
      ]; 
    //}

    await this.getOrganisations();

    await this.getLoggedInUserDetails();
    
    // if(this.role === 'IDRBTADMIN'){
    //   await this.getContactOfficersDetails(0);
    // }else if(this.role != 'IDRBTADMIN' && parseInt(this.organisationId) > 0){
      // await this.getContactOfficersDetails(parseInt(this.organisationId));
    //}

    //this.isButtonDisabled();

  }

  async getContactUsers(){
    //if(this.selectedOrganisation < 1){
      await this.getContactOfficersDetails(this.selectedOrganisation);
      this.validateAddUser();
    //}
  }

  contactDetailsList: any[] = [];
  async getContactOfficersDetails(selectedOrganisationId: number){
    //console.log(selectedOrganisationId)
    if(selectedOrganisationId!=0){
      await lastValueFrom(this.contactDetailsService.getContactOfficersDetails(selectedOrganisationId)).then(
        response => {
          //console.log(response)
          if(response.status === HttpStatusCode.Ok){
            //console.log(response.body);
            this.contactDetailsList = response.body;
            this.usersDataSource.data = this.contactDetailsList;
            //console.log(this.contactDetailsList)
            this.contactDetailsList.forEach((item, index) => {
              item.ids= index+1; // Add originalIndex property to your data
            });
            this.usersDataSource.paginator = this.paginator;
            //console.log(this.sort)
            setTimeout(() => {
              this.usersDataSource.sort = this.sort;
              this.usersDataSource.sortingDataAccessor = (data: any, sortHeaderId: string) => {
                if (sortHeaderId === 'organisationName') {
                  const organisationName = data.organisationDetails.institutionName; // Use optional chaining
                  return organisationName || ''; // Handle null/undefined or empty userRoles
                } else {
                  return data[sortHeaderId]; // Default sorting for other columns
                }
              };
            }, 0);
            this.isLoadingData=false;
          }
        },error => {
          this.isLoadingData=false;
          if(error.status === HttpStatusCode.Unauthorized){
            this.navigateToSessionTimeout();
          }
        }
      )
      // this.isLoadingData=false
    }else{
      this.isLoadingData=false
    }
    
  }

  // async getUsersList(organisationId: number) {
  //   //console.log('Organisation ID:', organisationId);
  //   if (isNaN(organisationId) || organisationId <= 1) {
  //     //console.error('Invalid organisationId:', organisationId);
  //     //return;
  //   }
  //   await lastValueFrom(this.userService.getAllUsers(organisationId)).then(
  //     (response) => {
  //       if (response.status === HttpStatusCode.Ok) {
  //         //console.log(response.body);
  //         this.usersList = response.body;
  //         this.usersDataSource.data = this.usersList;
  //         this.usersDataSource.paginator = this.paginator;
  //         //console.log(this.sort)
  //         setTimeout(() => {
  //           this.usersDataSource.sort = this.sort;
  //           //console.log(this.sort)
  //           //console.log(this.usersDataSource.sort);
  //         }, 0);
  //       }
  //     },
  //     (error) => {
  //       if (error.status === HttpStatusCode.Unauthorized) {
  //         this.navigateToSessionTimeout();
  //       }
  //     }
  //   );
  // }

  navigateToDomainDetails(domainId: number){
    this.router.navigate(['/domain-details'],{queryParams:{domainId:domainId}});
  }

  navigateToSessionTimeout() {
    this.router.navigateByUrl('/session-timeout');
  }

  organisationDetails: any;
  async getOrganisationDetailsOfUser(organisationId: number){
    await lastValueFrom(this.organisationService
      .getOrganisationDetailsByOrganisationId(organisationId)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.user.organisationDetails = response.body;
          //console.log(this.user);
        }
      },error => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    )
  }

  clearData(){
    this.user.id = 0;
    this.user.userName = '';
    this.user.userId = '';
    this.user.role = '';
    this.user.encryptedPassword = '';
    this.user.mobileNumber = '';
    this.user.mobileNumber = '';
    this.user.confirmPassword = '';
  }
  clearAddUserData(){
    this.selectedOfficerToAdd=null;
    sessionStorage.removeItem('newAddUser');
  }

  adminOfficerDetails: any = null;
  technicalOfficerDetails: any = null;
  billingOfficerDetails: any = null;
  officerDetails:any=null;
  async getAdminOfficerDetails(id){
  //console.log(id)
  // return
    await lastValueFrom(this.contactDetailsService.getAdminOfficerDetailsById(id)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          //console.log(this.clickedContact)
          this.adminOfficerDetails = response.body;
          ////console.log(this.adminOfficerDetails)
        }
      },error => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    )
  }

  async getTechnicalOfficerDetails(id: number){
    await lastValueFrom(this.contactDetailsService.getTechnicalOfficerDetailsById(id)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.technicalOfficerDetails = response.body;
          ////console.log(this.technicalOfficerDetails)
        }
      },error => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    )
  }

  async getBillingOfficerDetails(id: number){
    await lastValueFrom(this.contactDetailsService.getBillingOfficerDetailsById(id)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.billingOfficerDetails = response.body;
        }
      },error => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    )
  }
  
  updateMessage: string = '';
  async updateAdminOfficerLoginStatus(adminOfficerDetails: any) {
    //console.log(adminOfficerDetails)
    // this.AdminOrganisationNameChange();
    this.AdminPersonNameChange();
    this.AdminDesignationNameChange();
    this.AdminMobileNameChange();
    this.AdminEmailNameChange();
    ////console.log('Sending Admin Details:', adminOfficerDetails);  
    if (this.personNameInput && this.designationNameInput && this.mobileNameInput && this.emailNameInput){

    try {
      const response = await lastValueFrom(this.contactDetailsService.updateAdminDetails(adminOfficerDetails));
       const response1 = await lastValueFrom(this.organisationService.getOrganisationDetailsByOrganisationId(adminOfficerDetails.organisationId));
      if (response.status === HttpStatusCode.Ok) {
        this.updateMessage = 'Admin Officer details updated successfully!';
        //console.log('Admin Officer details updated:', response);
        this.toastr.success(' updated successfully');
        //update contact officer details in Registry
        let updatedContactToNIXI = {
    contactId: 'DRADMIN' + adminOfficerDetails.administrativeContactId,
    contactFullName: adminOfficerDetails.adminFullName,
    organisationName: "TEST",
    city: adminOfficerDetails.city == null ? response1.body.city : adminOfficerDetails.city,
    state: adminOfficerDetails.state == null  ? response1.body.state : adminOfficerDetails.state,
    pincode: adminOfficerDetails.pincode == null ? response1.body.pincode : adminOfficerDetails.pincode,
    email: adminOfficerDetails.adminEmail,
    phone: adminOfficerDetails.adminAltPhone,
    dialingCode: adminOfficerDetails.adminAltCountryCode
  };
        await this.updateContactInRegistry(updatedContactToNIXI); 
        this.resetForm();
        window.location.reload();
      } else {
        this.updateMessage = 'Failed to update admin officer details.';
        //console.log('Failed to update:', response.status);
      }
    } catch (error) {
      //console.error('Error updating admin officer:', error);
      this.updateMessage = 'An error occurred while updating details.';
    }
  }}

  async updateContactInRegistry(contact: any){
    const response =await lastValueFrom(this.rgtrRgntOfficerDetailsService.updateContactInRegistry(contact));
    const isUpdated = response.body;
    if(isUpdated){
      this.toastr.success('Contact updated successfully in Registry')
    }else{
     // this.toastr.warning('Contact not present in registry to update');
    }
  }

  clearButton() {
    this.resetForm();
    document.getElementById('closeRegForm').click();

  }
  cancelButton(){
    this.resetForm();
    document.getElementById('closeRegForm2').click();
  }
  clearButtons() {
    this.resetForm();
    document.getElementById('closeRegForm1').click();

  }

  // resetForm() {
  //   this.orgNameInput = true;
  //   this.personNameInput = true;
  //   this.designationNameInput = true;
  //   this.mobileNameInput = true;
  //   this.emailNameInput = true;
  
   
  //   this.orgNameErrorMessage = '';
  //   this.personNameErrorMessage = '';
  //   this.designationNameErrorMessage = '';
  //   this.mobileNameErrorMessage = '';
  //   this.emailNameErrorMessage = '';
  // }


  
  async updateTechnicalOfficerLoginStatus(techDetails: any) {
  // Trigger change detection/input updates
  this.personNameChange();
  this.designationNameChange();
  this.mobileNameChange();
  this.emailNameChange();

  // Proceed only if all required inputs are present
  if (this.personNameInput && this.designationNameInput && this.mobileNameInput && this.emailNameInput) {
    try {
      const response = await lastValueFrom(this.contactDetailsService.updateTechDetails(techDetails));
      const response1 = await lastValueFrom(this.organisationService.getOrganisationDetailsByOrganisationId(techDetails.organisationId));
      if (response.status === HttpStatusCode.Ok) {
        this.toastr.success('Updated successfully');

        // Build updated object for registry if needed
        const updatedContactToNIXI = {
          contactId: 'DRTECH' + techDetails.technicalContactId,
          contactFullName: techDetails.techFullName,
          organisationName: "TEST",
          city: techDetails.city == null ? response1.body.city : techDetails.city,
          state: techDetails.state == null ? response1.body.state : techDetails.state,
          pincode: techDetails.pincode == null ? response1.body.pincode : techDetails.pincode,
          email: techDetails.techEmail,
          phone: techDetails.techAltPhone,
          dialingCode: techDetails.techAltCountryCode
        };

        await this.updateContactInRegistry(updatedContactToNIXI);

        this.resetForm();
        window.location.reload();
      }
    } catch (error) {
      // Optional: display error message
      //console.error('Error updating technical officer details', error);
      this.toastr.error('Failed to update details');
    }
  }
}


  async updateBillingOfficerLoginStatus(billDetails: any) {
    //console.log(billDetails)
  // this.billingOrganisationNameChange(); // Uncomment if needed
  this.billingPersonNameChange();
  this.billingdesignationNameChange();
  this.billingMobileNameChange();
  this.billingEmailNameChange();

  //console.log(billDetails);

  if (
    this.personNameInput &&
    this.designationNameInput &&
    this.mobileNameInput &&
    this.emailNameInput
  ) {
    try {
      const response = await lastValueFrom(this.contactDetailsService.updateBillDetails(billDetails));
      const response1 = await lastValueFrom(this.organisationService.getOrganisationDetailsByOrganisationId(billDetails.organisationId));
      if (response.status === HttpStatusCode.Ok) {
        this.toastr.success('Updated successfully');

        const updatedContactToNIXI = {
          contactId: 'DRBILL' + billDetails.organisationalContactId,
          contactFullName: billDetails.billFullName,
          organisationName: 'TEST',
          city: billDetails.city == null  ? response1.body.city : billDetails.city,
          state: billDetails.state == null ? response1.body.state : billDetails.state,
          pincode: billDetails.pincode == null ? response1.body.pincode : billDetails.pincode,
          email: billDetails.billEmail,
          phone: billDetails.billAltPhone,
          dialingCode: billDetails.billAltCountryCode,
        };

        await this.updateContactInRegistry(updatedContactToNIXI);
        this.resetForm();
        window.location.reload();
      }
    } catch (error) {
      //console.error('Error updating billing officer:', error);
      this.toastr.error('Update failed');
    }
  }
}

  documentsList: any[] = [];
  async getContactOfficerDocuments(contactType: string, organisationId: number){
    await lastValueFrom(this.contactDocumentsService.getContactOfficerDocuments(contactType,organisationId)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.documentsList = response.body;
          //console.log(this.documentsList);
        }
      }, error => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    )
    return this.documentsList;
  }

  async enableOrDisableLoginStatus(loginStatus: string, contactOfficerDetails: any){
    //first update the login status of contact officer and then create the user login for the contact officer
    if(contactOfficerDetails.contactRole === 'AdminOfficer'){
      await this.getAdminOfficerDetails(contactOfficerDetails.id);
      //before updating status
      await this.getContactOfficerDocuments("Administrative",this.adminOfficerDetails.organisationId);
      let count = 0;
      //console.log('exe')
      this.documentsList.forEach(doc => {
        if(doc.documentStatus === 'Approved'){
          count = count + 1;
          //console.log(count)
        }else{
          count = count - 1;
          //console.log(count)
        }
      });
      if(count === 3 && loginStatus === 'Approved'){
        this.adminOfficerDetails.loginStatus = 'Approved';
        await this.updateAdminOfficerLoginStatus(this.adminOfficerDetails);
      }else if(count < 3 && loginStatus === 'Approved'){
        this.toastr.error('Document verification pending.')
        return;
      }else if(count === 3 && loginStatus === 'Rejected'){
        this.adminOfficerDetails.loginStatus = 'Rejected';
        await this.updateAdminOfficerLoginStatus(this.adminOfficerDetails);
      }else if(count < 3 && loginStatus === 'Rejected'){
        this.toastr.error('Document verification pending');
        return;
      }
    }else if(contactOfficerDetails.contactRole === 'TechnicalOfficer'){
      await this.getTechnicalOfficerDetails(contactOfficerDetails.id);
      await this.getContactOfficerDocuments("Technical",this.technicalOfficerDetails.organisationId);
      let count = 0;
      //console.log('exe')
      this.documentsList.forEach(doc => {
        if(doc.documentStatus === 'Approved'){
          count = count + 1;
          //console.log(count)
        }else{
          count = count - 1;
          //console.log(count)
        }
      });
      if(count === 3){
        this.technicalOfficerDetails.loginStatus = loginStatus;
        await this.updateTechnicalOfficerLoginStatus(this.technicalOfficerDetails);
      }else{
        this.toastr.error('Document verification pending');
        return;
      }
    }else{
      await this.getBillingOfficerDetails(contactOfficerDetails.id);
      await this.getContactOfficerDocuments("Billing",this.billingOfficerDetails.organisationId);
      let count = 0;
      //console.log('exe')
      this.documentsList.forEach(doc => {
        if(doc.documentStatus === 'Approved'){
          count = count + 1;
          //console.log(count)
        }else{
          count = count - 1;
          //console.log(count)
        }
      });
      if(count === 3){
        this.billingOfficerDetails.loginStatus = loginStatus;
      await this.updateBillingOfficerLoginStatus(this.billingOfficerDetails);
      }else{
        this.toastr.error('Document verification pending');
        return;
      }
    }
    //create the new user based on login status
    if(loginStatus === 'Approved'){
      this.user.active = true;
    }else{
      this.user.active = false;
      this.toastr.error('Login Rejected');
      return;
    }
    this.user.userName = contactOfficerDetails.personName;
    this.user.userId = contactOfficerDetails.emailId;
    this.user.role = contactOfficerDetails.contactRole;
    this.user.mobileNumber = contactOfficerDetails.mobileNumber;
    this.user.createdByEmailId = this.userId;
    this.user.organisationId = contactOfficerDetails.organisationId;
    this.user.isOnboardingCompleted = true;
    await lastValueFrom(this.userService.saveUser(this.user)).then(
      response => {
        if(response.status === HttpStatusCode.Created){
          //console.log(response);
          this.toastr.success('Login approved');
          // if(this.role === 'IDRBTADMIN'){
          //    this.getContactOfficersDetails(0);
          // }else if(this.role != 'IDRBTADMIN' && parseInt(this.organisationId) > 0){
             this.getContactOfficersDetails(parseInt(this.organisationId));
         // }
        }
      },error => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }else if(error.status === HttpStatusCode.InternalServerError){
          this.toastr.error('Error while approving user... please try again !');
        }
      }
    )
  }

  /**
   * 
   * @param user 
   */
  // navigateToVerifyDocuments(user: any){
  //   var contactUserType = '';
  //   //console.log(user.contactRole)
  //   if(user.contactRole === 'Administrative Officer'){
  //     contactUserType = 'Administrative';
  //   }else if(user.contactRole === 'Technical Officer'){
  //     contactUserType = 'Technical';
  //   }else{
  //     contactUserType = 'Billing';
  //   }
  //   this.router.navigate(['/verify-documents'],
  //     {
  //       queryParams:{
  //         organisationId:user.organisationId,
  //         contactUserType: contactUserType,
  //         email:user.emailId
  //       }})
  // }
   navigateToVerifyDocuments(user: any){
      var contactUserType = '';
      sessionStorage.setItem('docEmail',user.emailId);
      sessionStorage.setItem('orgIdForDoc',user.organisationId);
      if(user.contactRole === 'Administrative Officer'){
        contactUserType = 'Administrative';
         sessionStorage.setItem('contactType',contactUserType);
      }else if(user.contactRole === 'Technical Officer'){
        contactUserType = 'Technical';
            sessionStorage.setItem('contactType',contactUserType);
      }else{
        contactUserType = 'Billing';
          sessionStorage.setItem('contactType',contactUserType);
      }
      this.router.navigateByUrl('/verify-documents')
    }

  userInActiveMap: Map<string, boolean> = new Map();
options: { label: string, value: string }[] = [
  { label: 'Finance Officer', value: 'Billing Officer' },
  { label: 'Technical Officer', value: 'Technical Officer' },
  { label: 'Administrative Officer', value: 'Administrative Officer' }
];
  selectedOfficerToAdd : string = null;
  selectedOrganisationId: number = 0;

  adminDocDetails :any
  techDocDetails :any 
  billDocDetails :any 
  orgDocDetails :any 

  SubmittedAdminDocs(adminDocs) {
    //console.log(adminDocs)
    this.adminDocDetails=adminDocs
   }
   submittedTechDocDetails(techDocs){
     //console.log(techDocs)
     this.techDocDetails=techDocs
   }
   submittedBillDocDetails(billDocs){
     //console.log(billDocs)
     this.billDocDetails=billDocs
   }
   SubmittedOrgDocs(orgDoc){
     //console.log(orgDoc);
     this.orgDocDetails=orgDoc;
   }

   /**
   * 
   */
   openTheContactDetailsModal:boolean=false;
   validateAddUser() {
    //console.log(this.contactDetailsList);
    sessionStorage.setItem('newAddUser', 'active');
    if(this.userRole=='Super Admin' && this.isOnboardingCompleted ==true){
      this.assetService.addOfficersText("AddOfficer")
    this.openTheContactDetailsModal=true;
  }
    // this.openTheContactDetailsModal=true;
   

    // this.options = ;
    //console.log(this.userInActiveMap);
    
    // document.getElementById("hiddenAddUser").click();
}

  closeTheModal(event){
    //console.log(event)
    this.resetForm();
    document.getElementById('closeContactDetailsModal').click();
    window.location.reload();
  }

  deleteAdminById(id: number, contactRole: string) {
    const confirmation = window.confirm('Are you sure you want to delete this data?');
    
    if (confirmation) {
      this.userService.deleteAdminById(id, contactRole).subscribe({
        next: (res) => {
          if (res.status === HttpStatusCode.NoContent) {
            this.toastr.success('Data deleted successfully');
            window.location.reload();
          } else {
            this.toastr.error('Failed to delete data');
          }
        },
        error: (err) => {
          //console.error('Error deleting data:', err);
          this.toastr.error('An error occurred while deleting data');
        },
      });
    } else {
      this.toastr.info('Data deletion cancelled');
    }
  }
  deleteBillingById(id: number, contactRole: string) {
    const confirmation = window.confirm('Are you sure you want to delete this data?');
    
    if (confirmation) {
      this.userService.deleteBillById(id, contactRole).subscribe({
        next: (res) => {
          if (res.status === HttpStatusCode.NoContent) {
            this.toastr.success('Data deleted successfully');
            window.location.reload();
          } else {
            this.toastr.error('Failed to delete data');
          }
        },
        error: (err) => {
          //console.error('Error deleting data:', err);
          this.toastr.error('An error occurred while deleting data');
        },
      });
    } else {
      this.toastr.info('Data deletion cancelled');
    }
  }
 
  deleteTechById(id: number, contactRole: string) {
    const confirmation = window.confirm('Are you sure you want to delete this data?');
    
    if (confirmation) {
      this.userService.deleteTechById(id, contactRole).subscribe({
        next: (res) => {
          if (res.status === HttpStatusCode.NoContent) {
            this.toastr.success('Data deleted successfully');
            window.location.reload();
          } else {
            this.toastr.error('Failed to delete data');
          }
        },
        error: (err) => {
          //console.error('Error deleting data:', err);
          this.toastr.error('An error occurred while deleting data');
        },
      });
    } else {
      this.toastr.info('Data deletion cancelled');
    }
  }

  orgNameInput: boolean = true;
  orgNameErrorMessage: string = '';
  isValidOrgName: boolean = false;
  
  organisationNameChange() {
    const orgName = this.technicalOfficerDetails.organisationName;
  
    if (!orgName) {
      this.orgNameInput = false;
      this.orgNameErrorMessage = 'Please enter organisation name to save';
      this.isValidOrgName = false; // Validation failed
    } else if (orgName.length <= 3) {
      this.orgNameInput = false;
      this.orgNameErrorMessage = 'Organisation name should be a minimum of 3 characters to save';
      this.isValidOrgName = false; // Validation failed
    } else {
      this.orgNameInput = true;
      this.orgNameErrorMessage = '';
      this.isValidOrgName = true; // Validation passed
    }
  }
  billingOrganisationNameChange(){
    const orgName = this.billingOfficerDetails.organisationName;
  
    if (!orgName) {
      this.orgNameInput = false;
      this.orgNameErrorMessage = 'Please enter organisation name to save';
      this.isValidOrgName = false; // Validation failed
    } else if (orgName.length <= 3) {
      this.orgNameInput = false;
      this.orgNameErrorMessage = 'Organisation name should be a minimum of 3 characters to save';
      this.isValidOrgName = false; // Validation failed
    } else {
      this.orgNameInput = true;
      this.orgNameErrorMessage = '';
      this.isValidOrgName = true; // Validation passed
    }
  }

  AdminOrganisationNameChange(){
    const orgName = this.adminOfficerDetails.organisationName;
  
    if (!orgName) {
      this.orgNameInput = false;
      this.orgNameErrorMessage = 'Please enter organisation name to save';
      this.isValidOrgName = false; // Validation failed
    } else if (orgName.length <= 3) {
      this.orgNameInput = false;
      this.orgNameErrorMessage = 'Organisation name should be a minimum of 3 characters to save';
      this.isValidOrgName = false; // Validation failed
    } else {
      this.orgNameInput = true;
      this.orgNameErrorMessage = '';
      this.isValidOrgName = true; // Validation passed
    }
  }

  personNameInput: boolean = true;
  personNameErrorMessage: string = '';
  isValidPersonName: boolean = false;
  personNameChange() {
    const personName = this.technicalOfficerDetails.techFullName?.trim(); // Trim spaces from the input
  
    // Check if the person name is empty
    if (!personName) {
      this.personNameInput = false;
      this.personNameErrorMessage = 'Please enter person name to save';
      this.isValidPersonName = false; // Validation failed
    }
    // Check if the person name has less than or equal to 3 characters
    // else if (personName.length <= 3) {
    //   this.personNameInput = false;
    //   this.personNameErrorMessage = 'Person name should be a minimum of 3 characters to save';
    //   this.isValidPersonName = false; // Validation failed
    // } 
    else {
      // If person name is valid (not empty and more than 3 characters)
      this.personNameInput = true;
      this.personNameErrorMessage = '';
      this.isValidPersonName = true; // Validation passed
    }
  }
  
  billingPersonNameChange(){
    const personName = this.billingOfficerDetails.billFullName?.trim(); // Trim spaces from the input
  
    // Check if the person name is empty
    if (!personName) {
      this.personNameInput = false;
      this.personNameErrorMessage = 'Please enter person name to save';
      this.isValidPersonName = false; // Validation failed
    }
    // Check if the person name has less than or equal to 3 characters
    // else if (personName.length <= 3) {
    //   this.personNameInput = false;
    //   this.personNameErrorMessage = 'Person name should be a minimum of 3 characters to save';
    //   this.isValidPersonName = false; // Validation failed
    // }
     else {
      // If person name is valid (not empty and more than 3 characters)
      this.personNameInput = true;
      this.personNameErrorMessage = '';
      this.isValidPersonName = true; // Validation passed
    }
  }

  AdminPersonNameChange(){
    const personName = this.adminOfficerDetails.adminFullName?.trim(); // Trim spaces from the input
  
    // Check if the person name is empty
    if (!personName) {
      this.personNameInput = false;
      this.personNameErrorMessage = 'Please enter person name to save';
      this.isValidPersonName = false; // Validation failed
    }
    // Check if the person name has less than or equal to 3 characters
    // else if (personName.length <= 3) {
    //   this.personNameInput = false;
    //   this.personNameErrorMessage = 'Person name should be a minimum of 3 characters to save';
    //   this.isValidPersonName = false; // Validation failed
    // }
     else {
      // If person name is valid (not empty and more than 3 characters)
      this.personNameInput = true;
      this.personNameErrorMessage = '';
      this.isValidPersonName = true; // Validation passed
    }
  }


  designationNameInput: boolean = true;
  designationNameErrorMessage: string = '';
  isValidDesignationName: boolean = false;

  designationNameChange() {
    const desName = this.technicalOfficerDetails.techDesignation?.trim(); // Trim the input to remove leading/trailing spaces
  
    // Check if designation name is empty
    if (!desName) {
      this.designationNameInput = false;
      this.designationNameErrorMessage = 'Please enter designation name to save';
      this.isValidDesignationName = false; // Validation failed
    }
    // Check if designation name length is less than or equal to 3
    else if (desName.length < 2) {
      this.designationNameInput = false;
      this.designationNameErrorMessage = 'Designation name should be a minimum of 2 characters to save';
      this.isValidDesignationName = false; // Validation failed
    } else {
      // If the input is valid (non-empty, and length greater than 3)
      this.designationNameInput = true;
      this.designationNameErrorMessage = '';
      this.isValidDesignationName = true; // Validation passed
    }
  }
  
  billingdesignationNameChange(){
    const desName = this.billingOfficerDetails.billDesignation?.trim(); // Trim the input to remove leading/trailing spaces
  
    // Check if designation name is empty
    if (!desName) {
      this.designationNameInput = false;
      this.designationNameErrorMessage = 'Please enter designation name to save';
      this.isValidDesignationName = false; // Validation failed
    }
    // Check if designation name length is less than or equal to 3
    else if (desName.length < 2) {
      this.designationNameInput = false;
      this.designationNameErrorMessage = 'Designation name should be a minimum of 2 characters to save';
      this.isValidDesignationName = false; // Validation failed
    } else {
      // If the input is valid (non-empty, and length greater than 3)
      this.designationNameInput = true;
      this.designationNameErrorMessage = '';
      this.isValidDesignationName = true; // Validation passed
    }
  }

  AdminDesignationNameChange(){
    const desName = this.adminOfficerDetails.adminDesignation?.trim(); // Trim the input to remove leading/trailing spaces
  
    // Check if designation name is empty
    if (!desName) {
      this.designationNameInput = false;
      this.designationNameErrorMessage = 'Please enter designation name to save';
      this.isValidDesignationName = false; // Validation failed
    }
    // Check if designation name length is less than or equal to 3
    else if (desName.length < 2) {
      this.designationNameInput = false;
      this.designationNameErrorMessage = 'Designation name should be a minimum of 2 characters to save';
      this.isValidDesignationName = false; // Validation failed
    } else {
      // If the input is valid (non-empty, and length greater than 3)
      this.designationNameInput = true;
      this.designationNameErrorMessage = '';
      this.isValidDesignationName = true; // Validation passed
    }
  }

  mobileNameInput: boolean = true;
  mobileNameErrorMessage: string = '';
  isValidMobileName: boolean = false;

  mobileNameChange() {
  const mobileName = this.technicalOfficerDetails.techAltPhone;

  // Check if the mobile number is empty
  if (!mobileName) {
    this.mobileNameInput = false;
    this.mobileNameErrorMessage = 'Please enter mobile number to save';
    this.isValidMobileName = false;
  }
  // Check if the mobile number has exactly 10 digits AND the first digit is greater than 5
  else if (!/^[6-9]\d{9}$/.test(mobileName)) {
    this.mobileNameInput = false;
    this.mobileNameErrorMessage = 'Mobile number must be 10 digits long and start with a digit from 6 to 9.';
    this.isValidMobileName = false;
  } else {
    // If valid mobile number (exactly 10 digits and first digit > 5)
    this.mobileNameInput = true;
    this.mobileNameErrorMessage = '';
    this.isValidMobileName = true;
  }
}
  billingMobileNameChange() {
  const mobileName = this.billingOfficerDetails.billAltPhone;

  // Check if the mobile number is empty
  if (!mobileName) {
    this.mobileNameInput = false;
    this.mobileNameErrorMessage = 'Please enter mobile number to save.';
    this.isValidMobileName = false;
  }
  // Check if the mobile number has exactly 10 digits AND starts with a digit from 6 to 9
  else if (!/^[6-9]\d{9}$/.test(mobileName)) {
    this.mobileNameInput = false;
    this.mobileNameErrorMessage = 'Mobile number must be 10 digits long and start with a digit from 6 to 9.';
    this.isValidMobileName = false;
  } else {
    // If valid mobile number (exactly 10 digits and first digit 6-9)
    this.mobileNameInput = true;
    this.mobileNameErrorMessage = '';
    this.isValidMobileName = true;
  }
}
  AdminMobileNameChange(){
  const mobileName = this.adminOfficerDetails.adminAltPhone;

  // Check if the mobile number is empty
  if (!mobileName) {
    this.mobileNameInput = false;
    this.mobileNameErrorMessage = 'Please enter mobile number to save.';
    this.isValidMobileName = false;
  }
  // Check if the mobile number has exactly 10 digits AND starts with a digit from 6 to 9
  else if (!/^[6-9]\d{9}$/.test(mobileName)) {
    this.mobileNameInput = false;
    this.mobileNameErrorMessage = 'Mobile number must be 10 digits long and start with a digit from 6 to 9.';
    this.isValidMobileName = false;
  } else {
    // If valid mobile number (exactly 10 digits and first digit 6-9)
    this.mobileNameInput = true;
    this.mobileNameErrorMessage = '';
    this.isValidMobileName = true;
  }
}


  emailNameInput: boolean = true;
  emailNameErrorMessage: string = '';
  isValidemailName: boolean = false;
  emailNameChange() {
    const email = this.technicalOfficerDetails.techEmail;
  
    // Check if email is empty
    if (!email) {
      this.emailNameInput = false;
      this.emailNameErrorMessage = 'Please enter email to save';
      this.isValidemailName = false;
    }
    // Check if email matches the correct email pattern (basic email validation)
    else if (!this.isValidEmailFormat(email)) {
      this.emailNameInput = false;
      this.emailNameErrorMessage = 'Please enter a valid email address to save';
      this.isValidemailName = false;
    } else {
      // If email is valid
      this.emailNameInput = true;
      this.emailNameErrorMessage = '';
      this.isValidemailName = true;
    }
  }
  
  billingEmailNameChange(){
    const email = this.billingOfficerDetails.billEmail;
  
    // Check if email is empty
    if (!email) {
      this.emailNameInput = false;
      this.emailNameErrorMessage = 'Please enter email to save';
      this.isValidemailName = false;
    }
    // Check if email matches the correct email pattern (basic email validation)
    else if (!this.isValidEmailFormat(email)) {
      this.emailNameInput = false;
      this.emailNameErrorMessage = 'Please enter a valid email address to save';
      this.isValidemailName = false;
    } else {
      // If email is valid
      this.emailNameInput = true;
      this.emailNameErrorMessage = '';
      this.isValidemailName = true;
    }
  }
  AdminEmailNameChange(){
    const email = this.adminOfficerDetails.adminEmail;
  
    // Check if email is empty
    if (!email) {
      this.emailNameInput = false;
      this.emailNameErrorMessage = 'Please enter email to save';
      this.isValidemailName = false;
    }
    // Check if email matches the correct email pattern (basic email validation)
    else if (!this.isValidEmailFormat(email)) {
      this.emailNameInput = false;
      this.emailNameErrorMessage = 'Please enter a valid email address to save';
      this.isValidemailName = false;
    } else {
      // If email is valid
      this.emailNameInput = true;
      this.emailNameErrorMessage = '';
      this.isValidemailName = true;
    }
  }


  // Helper function to validate the email format
  isValidEmailFormat(email: string): boolean {
    const emailPattern =/^[a-zA-Z][a-zA-Z0-9.]*@[a-zA-Z0-9.]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(email);
  }


  
// isButtonDisabled(): boolean {
//   //////console.log(this.contactDetailsList)
//   return this.contactDetailsList?.length === 3 && this.contactDetailsList.every(contact => contact.isActive);
// }

isButtonDisabled(): boolean {
  //////console.log(this.contactDetailsList)
  if(this.userRole=='Super Admin' && this.isOnboardingCompleted ==true){
    return false
  }else
  return true;
}


private canDeleteOfficer(officerEmailToDelete: string, officerRoleToDelete: string, currentOfficers: any[]): boolean {
  // Ensure "Technical Officer One" if it's distinct
  const criticalRoles = ["Administrative Officer", "Technical Officer", "Technical Officer One", "Billing Officer"];
  
  const roleCounts: { [key: string]: number } = {};

  // Initialize counts for critical roles
  criticalRoles.forEach(role => roleCounts[role] = 0);

  // Count occurrences of critical roles
  currentOfficers.forEach(officer => {
    // This assumes each officer object has a single role.
    // If an officer object can have an array of roles, this loop needs to be adjusted.
    if (criticalRoles.includes(officer.contactRole)) {
      roleCounts[officer.contactRole]++;
    }
  });

  // Check if the specific email-role combination is a critical one
  // and if there's only one instance of that role
  if (criticalRoles.includes(officerRoleToDelete) && roleCounts[officerRoleToDelete] === 1) {
      let roleDisplayName = officerRoleToDelete; // Default to the actual role name

      // Change the display name specifically for "Billing Officer"
      if (officerRoleToDelete === "Billing Officer") {
          roleDisplayName = "Finance Officer";
      }

      this.toastr.error(
          `Cannot delete the only '${roleDisplayName}'. At least one officer with this role must remain.`,
          'Deletion Restricted'
      );
      return false; // Prevent deletion
  }

  // Find the officer to be deleted by both email and role.
  // This is the key change to handle multiple roles per email.
  const officerToDelete = currentOfficers.find(o => o.emailId === officerEmailToDelete && o.contactRole === officerRoleToDelete);

  if (!officerToDelete) {
      // If the specific officer (email and role combo) isn't found,
      // it means it's a valid case to allow deletion.
      //console.warn(`Officer with email ${officerEmailToDelete} and role ${officerRoleToDelete} not found.`);
      return true;
  }
  
  return true; // Allow deletion
}



  async deleteTheOfficerDetails(contactOfficerId: string, userEmail: string, userRole: string) {
  // Step 0: Pre-check before showing confirmation dialog
  if (!this.canDeleteOfficer(userEmail,userRole ,this.contactDetailsList)) {
    // Already handled via toastr inside canDeleteOfficer
    return;
  }

  // Step 1: Show confirmation dialog
  const confirmDeletion = window.confirm("Are you sure you want to delete the contact?");

  // Step 2: Proceed only if user confirmed
  if (confirmDeletion) {
    //console.log('User confirmed deletion for:', userEmail);

    try {
      const response = await lastValueFrom(
        this.userService.markAsDeletedByEmailId(userEmail, userRole)
      );

      this.toastr.success("Deleted Successfully");
      //console.log('Backend response after deletion:', response);

      await this.getDomainListOfOrg(this.selectedOrganisationId);
      let approvedDomainNames = this.domainList
          .filter(domain => domain.status === 'Active')
          .map(domain => `${domain.bankName}${domain.domainName}`);

      //console.log(approvedDomainNames)

      let  actualContactOfficerId = "";
      if(userRole === 'Administrative Officer'){
        actualContactOfficerId = "DRADMIN"+contactOfficerId;
      }else if(userRole === 'Technical Officer'){
       actualContactOfficerId = "DRTECH"+contactOfficerId;
      }else if(userRole === 'Billing Officer'){
         actualContactOfficerId = "DRBILL"+contactOfficerId;
      }
      
      // update domains in NIXI of this organisation to remove contact officer
      await this.updateApprovedDomainsInRegistryToRemoveContactOfficerOfAnOrganisation(actualContactOfficerId,
         userRole, approvedDomainNames);

      window.location.reload();

    } catch (error: any) {
      //console.error('Error during deletion:', error);

      if (error.status === 503) {
        this.toastr.error('Service Unavailable. Please try again after some time.', 'Deletion Failed');
      } else if (error.status === 500) {
        this.toastr.error('Please try after some time');
      } else if (error.status === 401) {
        this.toastr.error('Your session has expired. Please log in again.', 'Session Expired');
        this.router.navigate(['/session-timeout']);
      } else {
        this.toastr.error("Please try after some time");
      }
    }

  } else {
    // User clicked 'Cancel'
    this.toastr.info("Deletion cancelled.");
  }
}

domainList: any[] = []; 
getDomainListOfOrg(organisationId: number) {
  //console.log(this.selectedOrganisationId);
  return lastValueFrom(this.domainService.getAllDomainsByOrgId(organisationId)).then(
    response => {
      if (response.status === HttpStatusCode.Ok) {
        this.domainList = response.body;
        //console.log(this.domainList);
      } else {
        this.toastr.error('Error fetching domain list');
      }
    },
    error => {
      if (error.status === HttpStatusCode.Unauthorized) {
        this.navigateToSessionTimeout();
      } else {
        this.toastr.error('Error fetching domain list');
      }
    }
  );
}

  clickedContact:any;
  openEditOfficerModal(contact){
    //console.log(contact)
    this.selectedEditOfficer=contact.contactRole;
    //console.log(this.selectedEditOfficer)
    // return
    this.openTheEditContactDetailsModal=true;
  }
  

  async deleteContactOfficerFromRegistry(contactId: string){
    const response = await lastValueFrom(this.rgtrRgntOfficerDetailsService.deleteContactInRegistry(contactId));
    const isDeleted = response.body;
    if(isDeleted){
      this.toastr.success('Contact deleted from registry successfully.')
    }else{
      //console.log('contact not available in registry to delete,however its deleted from DB.')
    }
  }

  async updateApprovedDomainsInRegistryToRemoveContactOfficerOfAnOrganisation(contactId:string, 
    contactType:string, approvedDomainNames: string[]) {
      if(approvedDomainNames.length<=0){
        return;
      }
   const response = await lastValueFrom(this.rgtrRgntOfficerDetailsService
    .updateDomainRemoveContactInRegistry(contactId, 
      contactType,approvedDomainNames));

      const isRemoved = response.body;
      if(isRemoved){
        this.deleteContactOfficerFromRegistry(contactId);
      }

  }
}
