import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';

export interface User {
  id: number;
  name: string;
  userName: string;
  role: string[];
}

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private apiUrl = 'http://localhost:8080/auth'; // Altere para a URL da sua API de login
  private currentUserSubject: BehaviorSubject<User | null>;
  public currentUser: Observable<User | null>;

  constructor(private http: HttpClient, private router: Router) {
    const storedUser = this.getUserFromLocalStorage();
    this.currentUserSubject = new BehaviorSubject<User | null>(this.getUserFromLocalStorage());
    this.currentUser = this.currentUserSubject.asObservable();

    //if (storedUser) {
    //  this.redirectToUserDashboard(storedUser.role);
    //}
  }

  public get currentUserValue(): User | null {
    return this.currentUserSubject.value;
  }

  login(credentials: any): Observable<User> {
    return this.http.post<User>(`${this.apiUrl}/login`, credentials, { withCredentials: true }).pipe(
      tap((user: User) => {
        // O token é salvo diretamente nos cookies pelo Spring Boot.
        // Salvamos os dados do usuário no localStorage para acesso no frontend.
        localStorage.setItem('currentUser', JSON.stringify(user));
        this.currentUserSubject.next(user);
        this.redirectToUserDashboard(user.role);
      }),
      catchError(error => {
        console.error('Email ou senha incorretos', error);
        return of(null as any); // Retorna um Observable de null para indicar falha
      })
    );
  }

  enviaEmailResetSenha(email: string): Observable<string> { // 'esqueceuSenha' como no seu componente
    const headers = new HttpHeaders({ 'Content-Type': 'text/plain' });
    return this.http.post<string>(`${this.apiUrl}/esqueci-minha-senha`, email, { headers, responseType: 'text' as 'json' });
  }

  cadastraNovaSenha(senha: string, token: string): Observable<string>{
    const headers = new HttpHeaders({ 'Content-Type': 'text/plain' });
    const params = new HttpParams().set('token', token);
    return this.http.post<string>(`${this.apiUrl}/cadastroSenha`, senha, { headers, params, responseType: 'text' as 'json' });
  }

  logout() {
    this.http.post(`${this.apiUrl}/logout`, {}, {withCredentials: true})
    .subscribe({
      next: () =>{
        localStorage.removeItem('currentUser');
        this.currentUserSubject.next(null);
        this.router.navigate(['/login']);
        console.log('Logout bem-sucedido e cookie limpo pelo backend.');
      },
      error: (err) => {
        console.log('ERRO LOGOUT:', err);
        localStorage.removeItem('currentUser');
        this.currentUserSubject.next(null);
        this.router.navigate(['/login']);
      }
    });
  }

  isLoggedIn(): boolean {
    return this.currentUserSubject.value !== null;
  }

  hasRole(requiredRole: string): boolean {
    const user = this.currentUserSubject.value;
    return !!(user && user.role && user.role.includes(requiredRole));
  }

  private getUserFromLocalStorage(): User | null {
    const userString = localStorage.getItem('currentUser');
    if (userString) {
      return JSON.parse(userString) as User;
    }
    return null;
  }

  public redirectToUserDashboard(roles: string[]): void {
    if (roles.includes('ADM')) {
      this.router.navigate(['/dashboardadmin']);
    } else if (roles.includes('FUNC')) {
      this.router.navigate(['/dashboardusuario']);
    } else {
      this.router.navigate(['/login']);
    }
  }

  // Métodos para manipulação de cookies (se não estiver usando ngx-cookie-service)
  private getCookie(name: string): string | null {
    const nameEQ = name + '=';
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) === ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
  }

  private deleteCookie(name: string): void {
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=localhost;';
  }
}

