import { Component } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { AuthService } from "src/app/cores/services/auth.service";
import { HelpersService } from "src/app/cores/services/helpers.service";

@Component({
  selector: "app-auth",
  templateUrl: "./auth.component.html",
  styleUrls: ["./auth.component.scss"],
  host: { class: "flex-fill" },
})
export class AuthComponent {
  isShowPassword = false;
  isFormSubmitted = false;

  form: FormGroup;

  redirectUrl = "";

  constructor(
    private formBuilder: FormBuilder,
    private auth: AuthService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private helpers: HelpersService
  ) {
    this.form = this.formBuilder.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      remember_me: [false],
    });

    this.redirectUrl = this.activatedRoute.snapshot.queryParams["url"];
  }

  onSubmit() {
    if (this.form.valid) {
      this.isFormSubmitted = true;
      this.auth.login(this.form.value).subscribe({
        next: ({ data }) => {
          this.isFormSubmitted = false;
          this.auth.setToken(data.token);
          this.auth.setJwtToken(data.jwtToken);
          this.router.navigate([this.redirectUrl ?? "/dashboard"]);
        },
        error: (err) => {
          this.isFormSubmitted = false;
          this.helpers.toast("error", "Username atau Password salah!");
        },
      });
    }
  }
}
