import { FCMProvider } from '@admin/providers'
import { Component, inject, signal } from '@angular/core'
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'
import { Router, RouterLink } from '@angular/router'
import { LoadingButtonDirective } from '@frontend/shared'
import { translateSignal, TranslocoDirective } from '@jsverse/transloco'
import { HotToastService } from '@ngxpert/hot-toast'
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'
import { finalize } from 'rxjs'
import { AuthService } from '../../services'

/**
 * LoginComponent is used as the initial landing component when not logged in
 */
@UntilDestroy({ checkProperties: true })
@Component({
	selector: 'kadi-login',
	templateUrl: './login.component.html',
	imports: [TranslocoDirective, ReactiveFormsModule, LoadingButtonDirective, RouterLink],
})
export class LoginComponent {
	private readonly _router = inject(Router)
	private readonly _toast = inject(HotToastService)
	private readonly _formBuilder = inject(FormBuilder)
	private readonly _authService = inject(AuthService)
	private readonly fcmProvider = inject(FCMProvider)

	private readonly credentialsErrorTransalation = translateSignal('invalid_login_credentials_error')

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

	readonly loading = signal(false)

	/**
	 * Tries to log the user in with the given credentials from the form
	 */
	logIn() {
		if (this.form.invalid) return
		this.loading.set(true)

		const { email, password } = this.form.getRawValue()
		this._authService
			.login(email, password)
			.pipe(
				untilDestroyed(this),
				finalize(() => this.loading.set(false)),
			)
			.subscribe({
				next: () => {
					this._router.navigate(['dashboard']).then(() => {
						this.fcmProvider.subscribe()
					})
				},
				error: (error) => {
					if (error.status === 401) {
						this._toast.error(this.credentialsErrorTransalation())
					} else {
						this._toast.error(error.message)
					}
				},
			})
	}
}
