import { Component, OnInit } from '@angular/core';
import { DomainService } from '../rgnt-domain/service/domain.service';
import { ToastrService } from 'ngx-toastr';
import { DomSanitizer } from '@angular/platform-browser';
import { Modal } from 'bootstrap';
import { CommonModule } from '@angular/common';
import { ViewChild, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import * as CryptoJS from 'crypto-js';
// import { environment } from '../environments/environment.development';
import { environment } from '../environments/environment';


@Component({
    selector: 'app-rgtr-renewal-request',
    templateUrl: './rgtr-renewal-request.component.html',
    styleUrls: ['./rgtr-renewal-request.component.css'],
    standalone: false
})
export class RgtrRenewalRequestComponent implements OnInit {
@ViewChild('renewalModalRef') modalRef!: ElementRef;

  renewals: any[] = [];
  selectedRenewal: any;

  paymentRecieptPdf: any;
  openReciptasPdf: boolean = false;

  // ===== DSC =====
isDscChecked = false;
isDscVerified = false;
showDscModal = false;
 isLoading : boolean = false;
isDscLoading = false;

tokens: any[] = [];
certificates: any[] = [];

selectedToken: any = "";
selectedCertificate: any = "";
tokenPassword: string = "";

dscSignedData = "";
dscCertificate = "";
payloadToSign = "";

  constructor(
    private domainService: DomainService,
    private toastrService: ToastrService,
    private sanitizer: DomSanitizer,
      private router: Router,
      private http: HttpClient,
  ) {}

  ngOnInit(): void {
    
    this.loadRenewals(); // your API call

  }
  private readonly EMUDHRA_URL = 'https://localhost.emudhra.com:26769';
  // ================= LOAD =================
  loadRenewals() {
    this.domainService.getRenewalsForRegistrar().subscribe({
      next: (res: any) => {
        this.renewals = res || [];

        this.filteredRenewals = [...this.renewals];
      },
      error: () => {
        this.toastrService.error("Failed to load renewal requests");
      }
    });
  }

  // ================= OPEN =================
  // openModal(r: any) {
  //   this.selectedRenewal = r;
  //   this.fetchReceipt(r.domainId, r.renewalId);
  // }

  openModal(r: any) {

  this.selectedRenewal = r;

  this.paymentRecieptPdf = null;
  this.openReciptasPdf = false;

  this.fetchReceipt(r.domainId, r.renewalId);
}

  canViewReceipt(r: any): boolean {

  const status = r.paymentStatus
    ?.trim()
    .toLowerCase()
    .replace(/_/g, ' ');

  return status === 'payment under review' ||
         status === 'payment approved' ||
         status === 'renewed';
}
  // ================= FETCH RECEIPT =================
  fetchReceipt(domainId: number, renewalId: number) {

    this.domainService.getRenewalPaymentReceipt(domainId, renewalId)
      .subscribe({
        next: (res: any) => {

          console.log("Receipt API:", res);

          if (res?.renewalPaymentReceipt) {
            this.displayPaymentPdf(res.renewalPaymentReceipt);
            this.openReciptasPdf = true;
          } else {
            this.toastrService.warning("Receipt not found");
          }
        },
        error: () => {
          this.toastrService.error("Unable to fetch receipt");
        }
      });
  }

  // ================= PDF =================
  displayPaymentPdf(binaryData: any) {

    let blob: Blob;

    if (typeof binaryData === 'string') {
      const binaryString = atob(binaryData);
      const bytes = new Uint8Array(binaryString.length);

      for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }

      blob = new Blob([bytes], { type: 'application/pdf' });
    } else {
      blob = new Blob([new Uint8Array(binaryData)], { type: 'application/pdf' });
    }

    const pdfUrl = URL.createObjectURL(blob);
    this.paymentRecieptPdf =
      this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl);
  }

  // ================= APPROVE =================
  // approveRenewal() {

  //   const renewalId = this.selectedRenewal?.renewalId;
  //   if (!renewalId) return;

  //   this.domainService.approveRenewal(renewalId).subscribe({
  //     next: () => {
  //       this.toastrService.success("Approved & sent to NIXI");

  //       this.loadRenewals();
  //       this.closeModal();
  //     },
  //     error: () => {
  //       this.toastrService.error("Approval failed");
  //       this.closeModal();
  //     }
  //   });
  // }
  
   approvingMap: { [key: number]: boolean } = {};
//  approveRenewal() {

//     const renewalId = this.selectedRenewal?.renewalId;
//     if (!renewalId) return;

//     // 🔥 prevent duplicate only for THIS row
//     if (this.approvingMap[renewalId]) return;

//     this.approvingMap[renewalId] = true;

//     this.domainService.approveRenewal(renewalId).subscribe({
//       next: (res: any) => {

//         const message =
//           res?.message || "Approved & sent to NIXI";

//         this.toastrService.success(message);
//           this.closeModal();

//         // ✅ RELOAD FROM BACKEND (source of truth)
//         this.loadRenewals();

      

//         // keep disabled (no reset → since status becomes Renewed)
//       },
//       error: (err) => {

//         const backendMessage =
//           err?.error?.message ||
//           err?.error ||
//           "Approval failed";

//         this.toastrService.error(backendMessage);

//         // allow retry
//         this.approvingMap[renewalId] = false;
//       }
//     });
//   }

approveRenewal() {

  if (!this.selectedRenewal) {
    this.toastrService.error("Select renewal first");
    return;
  }

  this.isDscChecked = false;
  this.isDscVerified = false;

  this.tokens = [];
  this.certificates = [];
  this.selectedToken = "";
  this.selectedCertificate = "";
  this.tokenPassword = "";

  this.closeModal();

  this.showDscModal = true;

  this.getDscTokens();
}

getDscTokens() {

  this.isLoading = true; // ✅ START

  this.http.get(`${environment.apiURL}/dsc/getTokenRequest`)
    .subscribe({
      next: (res: any) => {

        const payload = {
          encryptedRequest: res.encryptedData,
          encryptionKeyID: res.encryptionKeyID
        };

        this.http.post(`https://localhost.emudhra.com:26769/DSC/ListToken`, payload)
          .subscribe({
            next: (emRes: any) => {

              this.http.get(`${environment.apiURL}/dsc/getTokenList?data=${encodeURIComponent(emRes.responseData)}`)
                .subscribe({
                  next: (finalRes: any) => {

                    this.tokens = finalRes.tokenNames || [];

                    if (this.tokens.length > 0) {
                      this.selectedToken = this.tokens[0];
                      this.onTokenSelect();
                    }

                    this.isLoading = false; // ✅ STOP
                  },
                  error: () => this.isLoading = false
                });

            },
            error: () => this.isLoading = false
          });

      },
      error: () => this.isLoading = false
    });
}
onTokenSelect() {

  this.isLoading = true; // ✅ START

  this.http.get(`${environment.apiURL}/dsc/getCertificateRequest?keyStoreDisplayName=${this.selectedToken}`)
    .subscribe({
      next: (res: any) => {

        const payload = {
          encryptedRequest: res.encryptedData,
          encryptionKeyID: res.encryptionKeyID
        };

        this.http.post(`https://localhost.emudhra.com:26769/DSC/ListCertificate`, payload)
          .subscribe({
            next: (emRes: any) => {

              this.http.post(`${environment.apiURL}/dsc/getCertificateList`, {
                encryptedCertificateData: emRes.responseData
              }).subscribe({
                next: (finalRes: any) => {

                  this.certificates = finalRes.certificates || [];

                  if (this.certificates.length > 0) {
                    this.selectedCertificate = this.certificates[0];
                  }

                  this.isLoading = false; // ✅ STOP
                },
                error: () => this.isLoading = false
              });

            },
            error: () => this.isLoading = false
          });

      },
      error: () => this.isLoading = false
    });
}

closeDscModal() {
  this.showDscModal = false;

  // reset values
  this.selectedToken = "";
  this.selectedCertificate = "";
  this.tokenPassword = "";
}
signWithDSC() {

  if (!this.selectedRenewal?.renewalId) {
    this.toastrService.error("Invalid renewal");
    return;
  }

  if (!this.selectedToken || !this.selectedCertificate || !this.tokenPassword) {
    this.toastrService.error("Select token, certificate & enter password");
    return;
  }

  this.isLoading = true; // ✅ START

  const payloadObject = {
    renewalId: this.selectedRenewal.renewalId,
    domainId: this.selectedRenewal.domainId,
    organisationId: this.selectedRenewal.organisationId,
    action: "APPROVAL",
    approvedBy: localStorage.getItem('email'),
    timestamp: new Date().toISOString()
  };

  this.payloadToSign = JSON.stringify(payloadObject);

  const hash = CryptoJS.SHA256(this.payloadToSign).toString();

  const signReq = {
    keyId: this.selectedCertificate.keyId,
    keyStoreDisplayName: this.selectedToken,
    keyStorePassPhrase: this.tokenPassword,
    dataType: 'TextPKCS7',
    dataToSign: hash
  };

  this.http.post(`${environment.apiURL}/dsc/getSigningRequest`, signReq)
    .subscribe({
      next: (res: any) => {

        const payload = {
          encryptedRequest: res.encryptedData,
          encryptionKeyID: res.encryptionKeyID
        };

        this.http.post(`https://localhost.emudhra.com:26769/DSC/PKCSSign`, payload)
          .subscribe({
            next: (emRes: any) => {

              this.dscSignedData = emRes.responseData;
              this.dscCertificate = JSON.stringify(this.selectedCertificate);

              this.saveApprovalSignature();
            },
            error: () => this.isLoading = false
          });

      },
      error: () => this.isLoading = false
    });
}
saveApprovalSignature() {

  this.http.post(`${environment.apiURL}/dsc/registrar/approval/saveSignature`, {
    renewalId: this.selectedRenewal.renewalId,
    domainId: this.selectedRenewal.domainId,
    organisationId: this.selectedRenewal.organisationId,
    signedPayload: this.payloadToSign,
    encryptedSignedData: this.dscSignedData,
    certificate: this.dscCertificate,
    approvedBy: localStorage.getItem('email')
  }).subscribe({
    next: () => {

      this.isLoading = false; // ✅ FINAL STOP

      this.isDscVerified = true;
      this.showDscModal = false;

      this.toastrService.success("DSC Verified");

      this.finalApprove();
    },
    error: (err) => {
      this.isLoading = false; // ✅ STOP ON ERROR
      this.toastrService.error(err?.error || "DSC verification failed");
    }
  });
}

finalApprove() {

  const renewalId = this.selectedRenewal?.renewalId;

  this.domainService.approveRenewal(renewalId).subscribe({
    next: () => {

      this.toastrService.success("Approved & sent to NIXI");

      this.loadRenewals();
      this.closeModal();
    }
  });
}
  // ================= REJECT =================
  rejectRenewal() {

    const renewalId = this.selectedRenewal?.renewalId;
    if (!renewalId) return;

    this.domainService.rejectRenewal(renewalId).subscribe({
      next: () => {
        this.toastrService.warning("Receipt rejected. Please upload again.");

        this.loadRenewals();
        this.closeModal();
      },
      error: () => {
        this.toastrService.error("Reject failed");
      }
    });
  }

  // ================= CLOSE =================
  // closeModal() {
  //   const modalEl = document.getElementById('renewalModal');
  //   const modal = Modal.getInstance(modalEl);
  //   modal?.hide();
  // }

//   closeModal() {
//   const modalEl = document.getElementById('renewalModal');

//   if (modalEl) {
//     // 🔥 ALWAYS create instance fresh
//     const modal = Modal.getOrCreateInstance(modalEl);
//     modal.hide();

//     // 🔥 IMPORTANT: cleanup backdrop (fix stuck UI)
//     document.body.classList.remove('modal-open');
//     const backdrops = document.getElementsByClassName('modal-backdrop');
//     while (backdrops.length > 0) {
//       backdrops[0].remove();
//     }
//   }
// }

closeModal() {
  const modalEl = document.getElementById('renewalModal');

  if (modalEl) {


    const modal = new Modal(modalEl);

    modal.hide();

    
    modalEl.classList.remove('show');
    modalEl.style.display = 'none';

    document.body.classList.remove('modal-open');

   
    const backdrops = document.querySelectorAll('.modal-backdrop');
    backdrops.forEach(el => el.remove());
  }
}

// goToDomainDetails(domainId: number) {

//   // ✅ Save current page data
//   sessionStorage.setItem('renewalsData', JSON.stringify(this.renewals));

//   this.router.navigate(['/domain-details'], {
//     queryParams: { domainId: domainId }
//   });
// }

searchDomainId: string = '';
searchPaymentStatus: string = '';
filteredRenewals: any[] = [];

applyFilters() {
  this.filteredRenewals = this.renewals.filter(r => {

    const matchesDomain =
      !this.searchDomainId ||
      r.domainId.toString().includes(this.searchDomainId);

    const matchesStatus =
      !this.searchPaymentStatus ||
      r.paymentStatus === this.searchPaymentStatus;

    return matchesDomain && matchesStatus;
  });
}

clearFilters() {
  this.searchDomainId = '';
  this.searchPaymentStatus = '';
  this.filteredRenewals = [...this.renewals];
}

}