import { HttpClient } from '@angular/common/http';
import { Component, signal } from '@angular/core';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { ToastrService } from "ngx-toastr";
import { jwtDecode } from "jwt-decode";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
})
export class LoginComponent {
  loginObj: any = {
    "username": "",
    "password": ""
  };
  errorMessage: string = '';
  isLoading: boolean = false;
  decodedToken: any;

  baseUrl: string;

  constructor(
    private http: HttpClient,
    private router: Router,
    private configService: ConfigService,
    private toastService: ToastrService,
    private translateService: TranslateService
  ) {
    this.baseUrl = this.configService.apiUrl;
    const savedLanguage = localStorage.getItem('language') || 'es';
    this.translateService.use(savedLanguage);
  }

  onLogin() {
    this.errorMessage = '';
    this.isLoading = true;

    if (!this.loginObj.username || !this.loginObj.password) {
      if (!this.loginObj.username) {
        document.getElementById('username')?.classList.add('invalid');
      } else {
        document.getElementById('username')?.classList.remove('invalid');
      }

      if (!this.loginObj.password) {
        document.getElementById('password')?.classList.add('invalid');
      } else {
        document.getElementById('password')?.classList.remove('invalid');
      }

      this.isLoading = false;
      return;
    }

    this.http.post(`${this.baseUrl}/auth/login`, this.loginObj).subscribe({
      next: (res: any) => {
        if (res.token) {
          localStorage.setItem('loginToken', res.token);
          localStorage.setItem('refreshToken', res.refreshToken);
          localStorage.setItem('username', this.loginObj.username);

          this.decodedToken = jwtDecode(res.token);
          localStorage.setItem('groupsView', this.decodedToken.groupsView);

          this.openSnackBar(false, 'Bienvenido ' + this.loginObj.username);
          this.router.navigateByUrl('/groups');
        }
        this.isLoading = false;
      },
      error: (err) => {
        this.isLoading = false;
        this.openSnackBar(true, 'Error al iniciar sesión: ' + err.error.message);
      }
    });
  }

  hide = signal(true);
  clickEvent(event: Event) {
    event.stopPropagation();
    this.hide.set(!this.hide());
  }

  openSnackBar(isError: boolean, message: string) {
    if (isError) {
      this.toastService.error(message, 'Error');
    } else {
      this.toastService.success(message, 'Éxito');
    }
  }

  changeLanguage(language: string) {
    localStorage.setItem('language', language);
    this.translateService.use(language);
  }
}
