import { NgIf } from '@angular/common';
import { Component, Renderer2 } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  FormsModule,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import { Router } from '@angular/router';
import { User } from '../../model/User';
import { LocalStorageService } from '../../services/localstorage.service';
import { LoginService } from '../../services/login.service';

@Component({
  selector: 'app-login-page',
  imports: [FormsModule, ReactiveFormsModule, NgIf],
  templateUrl: './login-page.component.html',
  styleUrl: './login-page.component.css',
})
export class LoginPageComponent {
  userForm: FormGroup;
  user: User = { login: '', password: '' };
  errorMessage: string = '';

  constructor(
    private loginService: LoginService,
    private fb: FormBuilder,
    private router: Router,
    private localStorageService: LocalStorageService,
    private renderer: Renderer2
  ) {
    this.userForm = this.fb.group({
      login: [this.user.login, [Validators.required, Validators.minLength(3)]],
      password: [
        this.user.password,
        [Validators.required, Validators.minLength(3)],
      ],
    });
  }

  public login() {
    if (this.userForm.invalid) {
      this.errorMessage = 'Veuillez remplir tous les champs';
      return;
    }

    this.user.login = this.userForm.value.login;
    this.user.password = this.userForm.value.password;

    this.loginService.login(this.user.login, this.user.password).subscribe({
      next: (response) => {
        console.log('Connexion OK: ', response);
        this.localStorageService.setToken(response.access_token);
        this.closeModal();
        setTimeout(() => {
          this.router.navigate(['/map']);
          window.location.reload(); // Pas ouf mais ça marche
        }, 500);
      },

      error: (response) => {
        console.log('Connexion KO: ', response.error.detail);
        this.errorMessage = response.error.detail;
      },
    });
  }

  private closeModal() {
    const modal = document.getElementById('close-login-modal');
    if (modal) {
      modal.click();
    }
  }
}
