import { Component, OnInit, ViewChild, AfterViewInit } from "@angular/core";
import { Router, ActivatedRoute } from "@angular/router";
import { CommonModule } from "@angular/common";
import {
    FormBuilder,
    FormGroup,
    ReactiveFormsModule,
    Validators,
} from "@angular/forms";
import { TranslateModule, TranslatePipe } from "@ngx-translate/core";
import { MatInput, MatInputModule } from "@angular/material/input";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatButtonModule } from "@angular/material/button";

import { first } from "rxjs/operators";

import { AuthenticationService } from "../../services/authentication.service";

@Component({
    selector: "app-login-user",
    templateUrl: "./login-user.component.html",
    styleUrls: ["./login-user.component.css"],
    imports: [
        CommonModule,
        MatFormFieldModule,
        ReactiveFormsModule,
        MatInputModule,
        TranslateModule,
        TranslatePipe,
        MatButtonModule,
    ],
})
export class LoginUserComponent implements OnInit {
    public loginForm: FormGroup;
    public loading = false;
    public submitted = false;
    public returnUrl: string;
    public error: string = "";

    constructor(
        private formBuilder: FormBuilder,
        private route: ActivatedRoute,
        private router: Router,
        private authenticationService: AuthenticationService,
    ) {
        if (this.authenticationService.currentUserValue) {
            this.router.navigate(["/"]);
        }
    }

    ngOnInit() {
        this.loginForm = this.formBuilder.group(
            {
                username: ["", [Validators.required, Validators.minLength(3)]],
                password: ["", [Validators.required]],
            },
            { updateOn: "submit" },
        );

        // get return url from route parameters or default to '/'
        this.returnUrl = this.route.snapshot.queryParams["returnUrl"] || "/";
    }

    get formCtrls() {
        return this.loginForm.controls;
    }

    public onLoginSubmit() {
        this.submitted = true;

        if (this.loginForm.valid) {
            this.loading = true;
            this.authenticationService
                .login(
                    this.formCtrls["username"].value,
                    this.formCtrls["password"].value,
                )
                .pipe(first())
                .subscribe({
                    complete: () => this.router.navigate([this.returnUrl]),
                    error: (error) => {
                        this.error = error.message;
                        this.loading = false;
                    },
                });
        }
    }
}
