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

import { first } from "rxjs/operators";

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

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

  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService,
    private translateService: TranslateService
  ) {
    // redirect to home if already logged in
    if (this.authenticationService.currentUserValue) {
      this.router.navigate(["/"]);
    }
  }

  ngOnInit() {
    this.createForm = this.formBuilder.group(
      {
        firstname: ["", [Validators.required, Validators.minLength(3)]],
        lastname: ["", [Validators.required, Validators.minLength(3)]],
        email: ["", [Validators.required, Validators.email]],
        username: ["", [Validators.required, Validators.minLength(3)]],
        password: [
          "",
          [
            Validators.required,
            Validators.pattern(
              "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[@$!%*#?&-_|]).{8,}$"
            ),
          ],
        ],
      },
      { updateOn: "blur" }
    );

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

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

  onCreateSubmit() {
    this.invalidForm = false;
    this.submitted = true;
    if (this.createForm.invalid) {
      this.invalidForm = true;
      return;
    }
    let createUser = new User();
    createUser.login = this.formCtrls["username"].value;
    createUser.password = this.formCtrls["password"].value;
    createUser.firstName = this.formCtrls["firstname"].value;
    createUser.lastName = this.formCtrls["lastname"].value;
    createUser.email = this.formCtrls["email"].value;
    createUser.language = this.translateService.getCurrentLang();
    this.authenticationService
      .create(createUser)
      .pipe(first())
      .subscribe({
        complete: () => this.router.navigate([this.returnUrl]),
        error: (error) => {
          this.error = error.message;
          this.invalidForm = false;
        },
      });
  }
}
