import { Component, OnInit } from "@angular/core";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { CompanyService } from "../../services/company.service";
import { AuthService } from "../../services/auth.service";

@Component({
  selector: "app-login",
  templateUrl: "./login.component.html",
  styleUrls: ["./login.component.scss"],
})
export class LoginComponent implements OnInit {
  private emailPattern =
    "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\\])";
  loginForm: FormGroup;
  hide: boolean = true;
  company: any;
  loginSuccess: boolean = false;
  loginError: boolean = false;
  companyLocalStorage: any;

  constructor(
    private fb: FormBuilder,
    private companyService: CompanyService,
    private authService: AuthService,
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.loginForm = this.fb.group({
      companyEmail: [
        "",
        [Validators.required, Validators.pattern(this.emailPattern)],
      ],
      password: ["", [Validators.required, Validators.minLength(6)]],
    });

    this.companyService.getCompanyById(1).subscribe((company) => {
      this.company = company;
    });
  }

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

  ngOnInit(): void {
    this.loginForm.patchValue({
      companyEmail: this.company.email,
      password: this.company.password,
    });
  }

  signin() {
    if (this.loginForm.invalid) {
      console.log("Form error");
      return;
    }

    const email = this.company.email;
    const password = this.company.password;

    if (
      this.loginForm.value.companyEmail !== email ||
      this.loginForm.value.password !== password
    ) {
      console.log("Invalid email or password");
      this.loginError = true;
      return;
    }

    this.loginSuccess = true;

    localStorage.setItem("companyData", JSON.stringify(this.company));

    this.companyLocalStorage = JSON.parse(
      localStorage.getItem("companyData") || "{}"
    );

    const isLoggedIn = this.authService.login(
      this.loginForm.value.companyEmail,
      this.loginForm.value.password
    );

    if (isLoggedIn) {
      setTimeout(() => {
        this.router.navigate(["company-information"]);
      }, 1000);

      console.log(true);
    } else {
      this.router.navigate(["/login"]);
    }

    this.loginForm.reset();
  }
}
