import { CommonModule, NgIf } from '@angular/common';
import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  FormsModule,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { User } from '../../model/User';
import { LocalStorageService } from '../../services/local-storage/local-storage.service';
import { LoginService } from '../../services/login/login.service';
import { ModalService } from '../../services/modal/modal.service';

@Component({
  selector: 'app-login-page',
  imports: [FormsModule, ReactiveFormsModule, NgIf, CommonModule],
  templateUrl: './login-page.component.html',
  styleUrl: './login-page.component.css',
})
export class LoginPageComponent {
  modalId: string = 'login-modal';
  userForm: FormGroup;
  user: User = { login: '', password: '' };
  errorMessage: string = '';
  isLoginModalOpen: boolean = false;
  private modalSub!: Subscription;

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

  ngOnInit() {
    this.modalSub = this.modalService
      .getModalState(this.modalId)
      .subscribe((open) => {
        this.isLoginModalOpen = open;
      });
  }

  ngOnDestroy() {
    this.modalSub.unsubscribe();
  }

  public login() {
    if (this.userForm.invalid) {
      this.errorMessage =
        'Veuillez remplir tous les champs (identifiant de 3 caractères et mot de passe de 6 caractères minimum)';
      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) => {
        this.localStorageService.setToken(response.access_token);
        this.localStorageService.setUsername(this.user.login)
        this.closeLoginModal();
        setTimeout(() => {
          this.router.navigate(['/map']);
          this.modalService.closeModal(this.modalId);
        }, 1);
      },

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

  openLoginModal() {
    this.modalService.openModal(this.modalId);
  }

  closeLoginModal() {
    this.modalService.closeModal(this.modalId);
  }

  openRegisterModal() {
    this.modalService.closeModal(this.modalId);
    this.modalService.openModal('register-modal');
  }
}
