import { UpperCasePipe } from '@angular/common'
import { Component, inject } from '@angular/core'
import { RouterLink } from '@angular/router'
import { BillingProfileResponse, DefaultService } from '@api-client/angular'
import { TranslocoDirective } from '@jsverse/transloco'
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'
import { finalize } from 'rxjs'
import { LucideChevronLeft } from '@lucide/angular'

@UntilDestroy({ checkProperties: true })
@Component({
	selector: 'kadi-billing-settings',
	templateUrl: './billing-settings.component.html',
	imports: [TranslocoDirective, RouterLink, UpperCasePipe, LucideChevronLeft],
})
export class BillingSettingsComponent {
	private readonly _apiService = inject(DefaultService)

	profile: BillingProfileResponse | undefined
	loading = false

	refreshUrl = window.location.origin
	redirectUrl = `${window.location.origin}/settings/billing`

	constructor() {
		this.loadProfile()
	}

	createProfile(): void {
		this.loading = true
		if (this.profile?.accountId) {
			this.updateProfile()
		} else {
			this._apiService
				.billingControllerCreateBillingProfile({ refreshUrl: this.refreshUrl, redirectUrl: this.redirectUrl })
				.pipe(
					untilDestroyed(this),
					finalize(() => (this.loading = false)),
				)
				.subscribe({
					next: (res) => {
						this.profile = { accountId: res.accountId }
						window.open(res.redirectUrl)
					},
				})
		}
	}

	updateProfile(): void {
		this.loading = true
		this._apiService
			.billingControllerGetOnBoardingUrl({ refreshUrl: this.refreshUrl, redirectUrl: this.redirectUrl })
			.pipe(
				untilDestroyed(this),
				finalize(() => (this.loading = false)),
			)
			.subscribe({
				next: (res) => {
					window.open(res.redirectUrl)
				},
			})
	}

	private loadProfile(): void {
		this.loading = true
		this._apiService
			.billingControllerFindBillingProfile()
			.pipe(
				untilDestroyed(this),
				finalize(() => (this.loading = false)),
			)
			.subscribe({
				next: (profile) => (this.profile = profile),
			})
	}
}
