import { Component, Input, OnInit, OnDestroy} from '@angular/core';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';

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

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

@Component({
    selector: 'confirm-skip-payment-model',
    templateUrl: './confirm-skip-payment-model.component.html',
    styleUrls: ['./confirm-skip-payment-model.component.scss']
})
export class ConfirmSkipPaymentModelComponent implements OnInit {
    @Input() confirmSkipPaymentModel!: NgbModalRef
    @Input() confirmSkipPaymentModelNo!: () => void
    constructor(
        private router: Router,
        private accountInfoService: AccountInfoService,
        private sessionService: SessionService,
        private localStorageService: LocalStorageService,
    ) { }

    ngOnInit(): void {}
    
    /**
     * Saves the payment step information for the user.
     * On success, refreshes the session and navigates to the license verification page.
     * Handles errors using the accountInfoService error callback.
     */
    saveUserInfoSubscribe!:Subscription;
    nextStep() {
        let paymentStepInfo = {
          'xu_payment_step': 1,
          'auto_validate': this.localStorageService.getItem('autoValidate')
        };
        this.saveUserInfoSubscribe = this.accountInfoService.saveUserInfo(paymentStepInfo)
        .pipe(
            catchError(() => {
                return throwError(() => new Error('ups sommething happend'));
            })
        ).subscribe({
            next: () => {
                this.sessionService.reCheckSession();
                if (this.localStorageService.getItem('autoValidate') === 'true') {
                    this.router.navigate(['/market/home']);
                } else {
                    this.router.navigate(['/market/licenseVerification']);
                }
            },
            error: (err: HttpErrorResponse) => {
                this.accountInfoService.errorCallBack(err);
            },
            complete: () => {
                this.confirmSkipPaymentModelNo();
            }
        });
    };
    
    ngOnDestroy(): void {
        this.saveUserInfoSubscribe?.unsubscribe();
    }
}
