// Angular Core
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';

// RxJs
import { Subscription, throwError, firstValueFrom } from 'rxjs';
import { catchError, filter } from "rxjs/operators";

// Services
import { SessionService } from 'src/app/services/session/session.service';
import { AccountInfoService } from 'src/app/services/accountInfo/account-info.service';

import { StripePaymentModelComponent } from 'src/app/components/stripe-payment-model/stripe-payment-model.component';

import { NgbModal, NgbModalConfig, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { environment } from 'src/environments/environment';

@Component({
  standalone: false,
  selector: 'app-payment-portal',
  templateUrl: './payment-portal.component.html',
  styleUrls: ['./payment-portal.component.scss']
})
export class PaymentPortalComponent implements OnInit, OnDestroy {
    renderMe: boolean = false;
    payMethodAdded: boolean = false;
    paymentMethodsSubscribe!:Subscription;
    showPaymentModalSubscribe!:Subscription;
    constructor(
      private sessionService : SessionService,
      private accountInfoService: AccountInfoService,
      private modalService: NgbModal,
      private router: Router
    ) { 
        this.sessionService.getAuth().then((response) => {
            this.renderMe = true;
        });
    }

    ngOnInit(): void {
        this.showStripePaymentModel();
    }
    
    /**
     * Opens the Stripe payment modal for setting up a payment method.
     * Subscribes to the addPayMethodStatus event to update the payment method status.
     */
    stripePaymentModel!: NgbModalRef
    showStripePaymentModel() {
        this.paymentMethodsSubscribe = this.accountInfoService
        .getAllPaymentMethods()
        .subscribe({
            next: (res: any) => {
                if (res.data !== false) {
                  this.payMethodAdded = true;
                  this.stripePaymentModel = this.modalService.open(StripePaymentModelComponent,{size: 'sm'});
                  this.stripePaymentModel.componentInstance.stripePaymentModel = this.stripePaymentModel;
                  this.stripePaymentModel.componentInstance.stripePaymentModelNo = this.stripePaymentModelNo;
                  this.stripePaymentModel.componentInstance.paymentMethodCards = res.data.cards;
                  this.stripePaymentModel.componentInstance.paymentMethodBank = res.data.bankAccounts;
                  this.stripePaymentModel.componentInstance.pendingBankPymentMethods = res.data?.pendingBankPayMethods || [];

                  // Subscribe to addPayMethodStatus event
                  this.stripePaymentModel.componentInstance.addPayMethodStatus.subscribe((data: any) => {
                      this.payMethodAdded = data.status;
                  });

                  this.stripePaymentModel.componentInstance.stripePaymentModelNo = () => {
                     this.router.navigate(['/market/home']);
                     this.stripePaymentModel.dismiss();
                  };
                }
            },
            error: (err: HttpErrorResponse) => {
              this.accountInfoService.errorCallBack(err);
            },
            complete: () => { }
        });
    };
    
    /**
     * Dismisses the Stripe payment modal.
     * @param action
     */
    stripePaymentModelNo(action: any) {
        this.stripePaymentModel.dismiss();
    };

  ngOnDestroy(){
    this.paymentMethodsSubscribe?.unsubscribe();
    this.showPaymentModalSubscribe?.unsubscribe();
  }
}

