import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { UserService } from '@users/user.service';
import { IconButtonComponent, IconButtonTypes, LoadingService } from '@iqser/common-ui';
import { User } from '@red/domain';
import { firstValueFrom } from 'rxjs';
import { TranslateModule } from '@ngx-translate/core';
import { NamePipe } from '@common-ui/users/name.pipe';

@Component({
    selector: 'redaction-reset-password',
    templateUrl: './reset-password.component.html',
    standalone: true,
    imports: [TranslateModule, NamePipe, ReactiveFormsModule, IconButtonComponent],
})
export class ResetPasswordComponent {
    readonly iconButtonTypes = IconButtonTypes;
    readonly form = this._getForm();
    @Input() user: User;
    @Output() readonly toggleResetPassword = new EventEmitter();

    constructor(
        private readonly _formBuilder: UntypedFormBuilder,
        private readonly _userService: UserService,
        private readonly _loadingService: LoadingService,
    ) {}

    async save() {
        this._loadingService.start();
        await firstValueFrom(
            this._userService.resetPassword(
                {
                    password: this.form.get('temporaryPassword').value,
                    temporary: true,
                },
                this.user.id,
            ),
        );
        this.toggleResetPassword.emit();
        this._loadingService.stop();
    }

    private _getForm(): UntypedFormGroup {
        return this._formBuilder.group({
            temporaryPassword: [null, Validators.required],
        });
    }
}
