import { Component, inject } from '@angular/core'
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'
import { RouterLink } 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 { finalize } from 'rxjs'

@UntilDestroy({ checkProperties: true })
@Component({
	selector: 'kadi-registration',
	templateUrl: './registration.component.html',
	imports: [TranslocoDirective, ReactiveFormsModule, LoadingButtonDirective, RouterLink],
})
export class RegistrationComponent {
	private readonly _toast = inject(HotToastService)
	private readonly _formBuilder = inject(FormBuilder)
	private readonly _apiService = inject(DefaultService)

	form = this._formBuilder.group({
		email: this._formBuilder.control('', { validators: [Validators.required, Validators.email], nonNullable: true }),
	})
	loading = false

	verifyEmail() {
		if (this.form.invalid) return
		this.loading = true

		const email = this.form.getRawValue().email
		this._apiService
			.authControllerVerifyEmail({ email })
			.pipe(
				untilDestroyed(this),
				finalize(() => (this.loading = false)),
			)
			.subscribe({
				next: () => {
					this._toast.success('Verification email has been sent, please check your inbox', { autoClose: false })
					this.form.reset()
				},
				error: (error) => {
					this._toast.error(error.message)
				},
			})
	}
}
