import { Component, inject } from '@angular/core'
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'
import { ActivatedRoute, Router } from '@angular/router'
import { DefaultService } from '@api-client/angular'
import { LoadingButtonDirective } from '@frontend/shared'
import { HotToastService } from '@ngxpert/hot-toast'
import { TranslocoDirective } from '@jsverse/transloco'
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'
import { combineLatest, finalize } from 'rxjs'

@UntilDestroy({ checkProperties: true })
@Component({
	selector: 'kadi-new-password',
	templateUrl: 'new-password.component.html',
	imports: [TranslocoDirective, ReactiveFormsModule, LoadingButtonDirective],
})
export class NewPasswordComponent {
	private readonly _router = inject(Router)
	private readonly _toast = inject(HotToastService)
	private readonly _apiService = inject(DefaultService)
	private readonly _activeRoute = inject(ActivatedRoute)
	private readonly _formBuilder = inject(NonNullableFormBuilder)

	loading = false
	error = ''

	form = this._formBuilder.group({
		token: this._formBuilder.control('', Validators.required),
		password: this._formBuilder.control('', { validators: [Validators.required, Validators.minLength(8)] }),
		confirmPassword: this._formBuilder.control('', { validators: [Validators.required, Validators.minLength(8)] }),
	})

	constructor() {
		const token = this._activeRoute.snapshot.queryParamMap.get('token')
		if (token) {
			this.verifyToken(token)
		} else {
			this._router.navigateByUrl('/auth/login')
		}

		combineLatest([this.form.controls.password.valueChanges, this.form.controls.confirmPassword.valueChanges])
			.pipe(untilDestroyed(this))
			.subscribe({
				next: ([password, confirmPassword]) => {
					this.error = password === confirmPassword ? '' : 'Passwords do not match'
				},
			})
	}

	save(): void {
		if (this.form.invalid) return

		const request = this.form.getRawValue()
		if (request.password !== request.confirmPassword) return

		this.loading = true
		this._apiService
			.authControllerResetPassword(request)
			.pipe(
				untilDestroyed(this),
				finalize(() => (this.loading = false)),
			)
			.subscribe({
				next: () => {
					this._toast.success('Your password has been successfully changed, redirecting to login...', {
						duration: 5000,
					})
					this._router.navigateByUrl('/auth/login')
				},
				error: (error) => {
					this._toast.error(error.message)
				},
			})
	}

	private verifyToken(token: string): void {
		this._apiService
			.authControllerVerifyEmailToken({ token })
			.pipe(untilDestroyed(this))
			.subscribe({
				next: () => {
					this.form.controls.token.setValue(token)
				},
				error: (error) => {
					this._toast.error(error.message)
					this._router.navigateByUrl('/auth/login')
				},
			})
	}
}
