import { CommonModule } from '@angular/common';
import { Component } 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 { RegisterService } from '../../services/register.service';

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

  constructor(
    private registerService: RegisterService,
    private fb: FormBuilder,
    private localStorageService: LocalStorageService,
    private router: Router
  ) {
    this.userForm = this.fb.group(
      {
        login: [
          this.user.login,
          [Validators.required, Validators.minLength(3)],
        ],
        password: [
          this.user.password,
          [Validators.required, Validators.minLength(6)],
        ],
        verifyPassword: ['', [Validators.required]],
      },
      { validator: this.passwordMatchValidator }
    );
  }

  passwordMatchValidator(formGroup: FormGroup) {
    const password = formGroup.get('password')?.value;
    const verifyPassword = formGroup.get('verifyPassword')?.value;

    return password === verifyPassword ? null : { mismatch: true };
  }

  public register() {
    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.registerService
      .register(this.user.login, this.user.password)
      .subscribe({
        next: (response) => {
          console.log('Register OK: ', response);
          this.localStorageService.setToken(response.access_token);
          this.closeRegisterModal();
          setTimeout(() => {
            this.router.navigate(['/map']);
          }, 1);
        },
        error: (response) => {
          console.log('Register KO: ', response.error.detail);
          this.errorMessage = response.error.detail;
        },
      });
  }

  openRegisterModal() {
    this.isRegisterModalOpen = true;
  }

  closeRegisterModal() {
    this.isRegisterModalOpen = false;
  }
}
