import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { StripeCardComponent } from '@aztrix/components/stripe-card';
import { PaymentsService, TierSubscriptionRepresentation, TierSubscriptionsService, } from '@aztrix/sdk';
import { BehaviorSubject, distinctUntilChanged, first, from, map, shareReplay, } from 'rxjs';
import * as i0 from "@angular/core";
import * as i1 from "@aztrix/sdk";
import * as i2 from "@angular/common";
import * as i3 from "@angular/forms";
import * as i4 from "@aztrix/icons";
import * as i5 from "@aztrix/components/button";
import * as i6 from "@aztrix/components/stripe-card";
import * as i7 from "@aztrix/components/payment-method";
import * as i8 from "@angular/material/legacy-form-field";
import * as i9 from "@angular/material/legacy-select";
import * as i10 from "@angular/material/legacy-core";
import * as i11 from "@angular/material/legacy-input";
import * as i12 from "@aztrix/components/chip";
import * as i13 from "@aztrix/helpers";
export class ConfirmTierPaymentComponent {
    constructor(_paymentsService, _tierSubscriptions) {
        this._paymentsService = _paymentsService;
        this._tierSubscriptions = _tierSubscriptions;
        this.confirm = new EventEmitter();
        this.cancel = new EventEmitter();
        this._paymentMethods$ = this._paymentsService
            .getPaymentMethods()
            .pipe(distinctUntilChanged(), shareReplay(1));
        this._emptyPaymentMethod = {
            id: null,
            card: null,
            created: null,
            type: null,
        };
        this._paymentMethodControl = new FormControl(this._emptyPaymentMethod);
        this._loading$ = new BehaviorSubject(false);
        this.promoCodeControl = new FormControl('');
        this.showPromoCode = false;
    }
    ngOnInit() {
        this._paymentMethods$.pipe(first()).subscribe((paymentMethods) => {
            if (paymentMethods?.length) {
                this._paymentMethodControl.setValue(paymentMethods[0]);
            }
        });
        this.promoCodeControl.valueChanges.pipe(distinctUntilChanged()).subscribe(() => {
            this.promoCodeControl.setValue(this.promoCodeControl.value.toUpperCase());
        });
    }
    changeMethod(event) {
        this._paymentMethodControl.setValue(event.value);
    }
    errorChanges(error) {
        if (!error) {
            this._stripeCard.cardErrors = undefined;
        }
    }
    pay() {
        if (this._paymentMethodControl?.value?.id || this.discount?.percentOff === 100) {
            this.confirm.next({
                paymentMethod: this._paymentMethodControl?.value,
                promoCode: this.promoCodeControl.value,
            });
        }
        else {
            this._loading$.next(true);
            from(this._stripeCard.createPaymentMethod())
                .pipe(map((paymentMethod) => {
                if (paymentMethod) {
                    this._paymentMethodControl.setValue(paymentMethod);
                }
                this._loading$.next(false);
                return this._stripeCard.cardErrors === undefined;
            }))
                .subscribe((valid) => {
                if (valid && this._paymentMethodControl?.value) {
                    this.confirm.next({
                        paymentMethod: this._paymentMethodControl?.value,
                        promoCode: this.promoCodeControl.value,
                    });
                }
            });
        }
    }
    applyPromotionCode() {
        if (this._loading$.value === true) {
            return;
        }
        this.promoCodeControl.setErrors(undefined);
        this._loading$.next(true);
        this._tierSubscriptions.getDiscountInfo(this.promoCodeControl.value).subscribe({
            next: (discount) => {
                this.discount = discount;
                if (!discount?.active) {
                    this.promoCodeControl.setErrors({ expired: true });
                }
                this._loading$.next(false);
            },
            error: () => {
                this.promoCodeControl.setErrors({ unknown: true });
                this._loading$.next(false);
            },
        });
    }
    blur() {
        if (!this.promoCodeControl.value) {
            this.showPromoCode = false;
        }
    }
}
ConfirmTierPaymentComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ConfirmTierPaymentComponent, deps: [{ token: i1.PaymentsService }, { token: i1.TierSubscriptionsService }], target: i0.ɵɵFactoryTarget.Component });
ConfirmTierPaymentComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.1.5", type: ConfirmTierPaymentComponent, selector: "ax-confirm-tier-payment", inputs: { tierSubscription: "tierSubscription" }, outputs: { confirm: "confirm", cancel: "cancel" }, viewQueries: [{ propertyName: "_stripeCard", first: true, predicate: ["cardDetails"], descendants: true }], ngImport: i0, template: "<div class=\"product-info\" *ngIf=\"tierSubscription\">\n  <h4>{{ tierSubscription.tier }}</h4>\n  <h2 class=\"price\" [ngClass]=\"{off: discount?.active}\">\n    {{ tierSubscription.price / 100 | currency: tierSubscription.currency?.toUpperCase() }}\n    <span>/ {{ 'label.month' | translate }}</span>\n  </h2>\n  <h2 class=\"price\" *ngIf=\"discount?.active\">\n    {{\n      tierSubscription.price / 100 - (tierSubscription.price / 10000) * (discount?.percentOff || 0)\n        | currency: tierSubscription.currency?.toUpperCase()\n    }}\n    <span>/ {{ 'label.month' | translate }}</span>\n  </h2>\n</div>\n\n<ax-button *ngIf=\"!showPromoCode\" icon=\"plus\" color=\"primary\" (click)=\"showPromoCode = true\">\n  {{ 'label.add-promocode' | translate }}\n</ax-button>\n\n<div class=\"promocode\" *ngIf=\"showPromoCode && !discount?.active\">\n  <mat-form-field appearance=\"outline\" class=\"c-input\" style=\"width: 100%\">\n    <mat-label>{{ 'label.promocode' | translate }}</mat-label>\n    <input\n      matInput\n      [formControl]=\"promoCodeControl\"\n      autofocus\n      (keydown.enter)=\"applyPromotionCode()\"\n      (blur)=\"blur()\"\n    />\n    <mat-error *ngIf=\"promoCodeControl?.invalid\">{{\n      (promoCodeControl.hasError('expired')\n        ? 'tiers.change.failed.snackbar.message.promoCode.expired'\n        : 'tiers.change.failed.snackbar.message.promoCode'\n      ) | translate\n    }}</mat-error>\n  </mat-form-field>\n  <ax-button\n    class=\"apply\"\n    *ngIf=\"promoCodeControl?.value\"\n    filled\n    [loading]=\"_loading$ | async\"\n    [disabled]=\"promoCodeControl.invalid\"\n    (click)=\"applyPromotionCode()\"\n    >{{ 'label.apply' | translate }}</ax-button\n  >\n</div>\n\n<div class=\"discount\" *ngIf=\"discount?.active\">\n  <ax-chip icon=\"tag\" removable (removed)=\"discount = undefined\">\n    <b>{{ promoCodeControl?.value }}</b>\n    <span>&nbsp;-{{ discount.percentOff }}%</span>\n  </ax-chip>\n  <div>\n    -\n    {{\n      (tierSubscription.price / 10000) * (discount?.percentOff || 0)\n        | currency: tierSubscription.currency?.toUpperCase()\n    }}\n  </div>\n</div>\n\n<ng-container *ngIf=\"!discount?.active || discount?.percentOff !== 100\">\n  <mat-form-field\n    appearance=\"outline\"\n    class=\"c-input\"\n    style=\"width: 100%\"\n    *ngIf=\"(_paymentMethods$ | async)?.length > 0\"\n  >\n    <mat-label>{{ 'payment.tab.billing.payment-methods' | translate }}</mat-label>\n    <mat-select\n      class=\"select\"\n      [(value)]=\"stripePaymentMethod\"\n      (selectionChange)=\"changeMethod($event)\"\n    >\n      <mat-select-trigger *ngIf=\"_paymentMethodControl?.value\">\n        <ax-payment-method\n          [method]=\"_paymentMethodControl?.value\"\n          [selectMode]=\"true\"\n        ></ax-payment-method>\n      </mat-select-trigger>\n\n      <mat-option *ngFor=\"let paymentMethod of _paymentMethods$ | async\" [value]=\"paymentMethod\">\n        <ax-payment-method [method]=\"paymentMethod\" [selectMode]=\"true\"></ax-payment-method>\n      </mat-option>\n      <mat-option [value]=\"_emptyPaymentMethod\">\n        <ax-payment-method [method]=\"emptyPaymentMethod\" [selectMode]=\"true\"></ax-payment-method>\n      </mat-option>\n    </mat-select>\n  </mat-form-field>\n\n  <div *ngIf=\"!_paymentMethodControl?.value.id\">\n    <ax-stripe-card\n      #cardDetails\n      [showErrors]=\"false\"\n      (errorChanges)=\"errorChanges($event)\"\n    ></ax-stripe-card>\n    <div class=\"errors\">\n      <div class=\"c-property-edit__error\" *ngIf=\"cardDetails.cardErrors\">\n        <ax-icon class=\"icon\" name=\"alert-circle\"></ax-icon>\n        <span>{{ 'stripe.' + cardDetails.cardErrors.code + '.error' | translate }}</span>\n      </div>\n    </div>\n  </div>\n</ng-container>\n\n<div class=\"h-button-wrapper\">\n  <ax-button color=\"danger\" (click)=\"cancel.next()\">{{ 'label.cancel' | translate }}</ax-button>\n  <ax-button filled color=\"primary\" (click)=\"pay()\" [loading]=\"_loading$ | async\">{{\n    (discount?.percentOff === 100 ? 'label.confirm' : 'label.pay') | translate\n  }}</ax-button>\n</div>\n", styles: [":host{display:block;padding:1rem 1rem .5rem}.price.off{text-decoration:line-through}.product-info{text-align:center;margin-bottom:2rem}.errors{margin-top:.25rem}.discount{display:flex;align-items:center;justify-content:space-between}.promocode{display:flex;gap:1rem}.promocode .apply{padding-top:1rem}\n"], dependencies: [{ kind: "directive", type: i2.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i2.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i2.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i3.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i3.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i3.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "component", type: i4.IconComponent, selector: "ax-icon", inputs: ["name", "inline"] }, { kind: "component", type: i5.ButtonComponent, selector: "ax-button" }, { kind: "component", type: i6.StripeCardComponent, selector: "ax-stripe-card", inputs: ["amount", "showErrors"], outputs: ["payedClicked", "errorChanges"] }, { kind: "component", type: i7.PaymentMethodComponent, selector: "ax-payment-method", inputs: ["method", "selectMode"] }, { kind: "directive", type: i8.MatLegacyError, selector: "mat-error", inputs: ["id"] }, { kind: "component", type: i8.MatLegacyFormField, selector: "mat-form-field", inputs: ["color", "appearance", "hideRequiredMarker", "hintLabel", "floatLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i8.MatLegacyLabel, selector: "mat-label" }, { kind: "component", type: i9.MatLegacySelect, selector: "mat-select", inputs: ["disabled", "disableRipple", "tabIndex"], exportAs: ["matSelect"] }, { kind: "directive", type: i9.MatLegacySelectTrigger, selector: "mat-select-trigger" }, { kind: "component", type: i10.MatLegacyOption, selector: "mat-option", exportAs: ["matOption"] }, { kind: "directive", type: i11.MatLegacyInput, selector: "input[matInput], textarea[matInput], select[matNativeControl],      input[matNativeControl], textarea[matNativeControl]", exportAs: ["matInput"] }, { kind: "component", type: i12.ChipComponent, selector: "ax-chip", inputs: ["icon", "removable"], outputs: ["removed"] }, { kind: "pipe", type: i2.AsyncPipe, name: "async" }, { kind: "pipe", type: i2.CurrencyPipe, name: "currency" }, { kind: "pipe", type: i13.TranslatePipe, name: "translate" }] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ConfirmTierPaymentComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ax-confirm-tier-payment', template: "<div class=\"product-info\" *ngIf=\"tierSubscription\">\n  <h4>{{ tierSubscription.tier }}</h4>\n  <h2 class=\"price\" [ngClass]=\"{off: discount?.active}\">\n    {{ tierSubscription.price / 100 | currency: tierSubscription.currency?.toUpperCase() }}\n    <span>/ {{ 'label.month' | translate }}</span>\n  </h2>\n  <h2 class=\"price\" *ngIf=\"discount?.active\">\n    {{\n      tierSubscription.price / 100 - (tierSubscription.price / 10000) * (discount?.percentOff || 0)\n        | currency: tierSubscription.currency?.toUpperCase()\n    }}\n    <span>/ {{ 'label.month' | translate }}</span>\n  </h2>\n</div>\n\n<ax-button *ngIf=\"!showPromoCode\" icon=\"plus\" color=\"primary\" (click)=\"showPromoCode = true\">\n  {{ 'label.add-promocode' | translate }}\n</ax-button>\n\n<div class=\"promocode\" *ngIf=\"showPromoCode && !discount?.active\">\n  <mat-form-field appearance=\"outline\" class=\"c-input\" style=\"width: 100%\">\n    <mat-label>{{ 'label.promocode' | translate }}</mat-label>\n    <input\n      matInput\n      [formControl]=\"promoCodeControl\"\n      autofocus\n      (keydown.enter)=\"applyPromotionCode()\"\n      (blur)=\"blur()\"\n    />\n    <mat-error *ngIf=\"promoCodeControl?.invalid\">{{\n      (promoCodeControl.hasError('expired')\n        ? 'tiers.change.failed.snackbar.message.promoCode.expired'\n        : 'tiers.change.failed.snackbar.message.promoCode'\n      ) | translate\n    }}</mat-error>\n  </mat-form-field>\n  <ax-button\n    class=\"apply\"\n    *ngIf=\"promoCodeControl?.value\"\n    filled\n    [loading]=\"_loading$ | async\"\n    [disabled]=\"promoCodeControl.invalid\"\n    (click)=\"applyPromotionCode()\"\n    >{{ 'label.apply' | translate }}</ax-button\n  >\n</div>\n\n<div class=\"discount\" *ngIf=\"discount?.active\">\n  <ax-chip icon=\"tag\" removable (removed)=\"discount = undefined\">\n    <b>{{ promoCodeControl?.value }}</b>\n    <span>&nbsp;-{{ discount.percentOff }}%</span>\n  </ax-chip>\n  <div>\n    -\n    {{\n      (tierSubscription.price / 10000) * (discount?.percentOff || 0)\n        | currency: tierSubscription.currency?.toUpperCase()\n    }}\n  </div>\n</div>\n\n<ng-container *ngIf=\"!discount?.active || discount?.percentOff !== 100\">\n  <mat-form-field\n    appearance=\"outline\"\n    class=\"c-input\"\n    style=\"width: 100%\"\n    *ngIf=\"(_paymentMethods$ | async)?.length > 0\"\n  >\n    <mat-label>{{ 'payment.tab.billing.payment-methods' | translate }}</mat-label>\n    <mat-select\n      class=\"select\"\n      [(value)]=\"stripePaymentMethod\"\n      (selectionChange)=\"changeMethod($event)\"\n    >\n      <mat-select-trigger *ngIf=\"_paymentMethodControl?.value\">\n        <ax-payment-method\n          [method]=\"_paymentMethodControl?.value\"\n          [selectMode]=\"true\"\n        ></ax-payment-method>\n      </mat-select-trigger>\n\n      <mat-option *ngFor=\"let paymentMethod of _paymentMethods$ | async\" [value]=\"paymentMethod\">\n        <ax-payment-method [method]=\"paymentMethod\" [selectMode]=\"true\"></ax-payment-method>\n      </mat-option>\n      <mat-option [value]=\"_emptyPaymentMethod\">\n        <ax-payment-method [method]=\"emptyPaymentMethod\" [selectMode]=\"true\"></ax-payment-method>\n      </mat-option>\n    </mat-select>\n  </mat-form-field>\n\n  <div *ngIf=\"!_paymentMethodControl?.value.id\">\n    <ax-stripe-card\n      #cardDetails\n      [showErrors]=\"false\"\n      (errorChanges)=\"errorChanges($event)\"\n    ></ax-stripe-card>\n    <div class=\"errors\">\n      <div class=\"c-property-edit__error\" *ngIf=\"cardDetails.cardErrors\">\n        <ax-icon class=\"icon\" name=\"alert-circle\"></ax-icon>\n        <span>{{ 'stripe.' + cardDetails.cardErrors.code + '.error' | translate }}</span>\n      </div>\n    </div>\n  </div>\n</ng-container>\n\n<div class=\"h-button-wrapper\">\n  <ax-button color=\"danger\" (click)=\"cancel.next()\">{{ 'label.cancel' | translate }}</ax-button>\n  <ax-button filled color=\"primary\" (click)=\"pay()\" [loading]=\"_loading$ | async\">{{\n    (discount?.percentOff === 100 ? 'label.confirm' : 'label.pay') | translate\n  }}</ax-button>\n</div>\n", styles: [":host{display:block;padding:1rem 1rem .5rem}.price.off{text-decoration:line-through}.product-info{text-align:center;margin-bottom:2rem}.errors{margin-top:.25rem}.discount{display:flex;align-items:center;justify-content:space-between}.promocode{display:flex;gap:1rem}.promocode .apply{padding-top:1rem}\n"] }]
        }], ctorParameters: function () { return [{ type: i1.PaymentsService }, { type: i1.TierSubscriptionsService }]; }, propDecorators: { tierSubscription: [{
                type: Input
            }], confirm: [{
                type: Output
            }], cancel: [{
                type: Output
            }], _stripeCard: [{
                type: ViewChild,
                args: ['cardDetails']
            }] } });
//# sourceMappingURL=data:application/json;base64, 