import { ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { inject } from '@angular/core';
import { Observable } from 'rxjs';

export const authGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
  const authService = inject(AuthService);
  const router = inject(Router);
  const userData = JSON.parse(localStorage.getItem('userData') || '');

  if (!localStorage.getItem('token')) {
    router.navigate(['/auth']);
    return false;
  }

  // Verificar si el usuario está autenticado
  if (localStorage.getItem('token')) {
    const userRole = userData[1];
    
    // Verificar si la ruta requiere un rol específico y si el rol del usuario es permitido
    if (route.data['role'] && route.data['role'].indexOf(userRole) === -1) {
      switch (userRole) {
        case 'PF':
          router.navigate(['/homePadres/main']);
          break;
        case 'AD':
          router.navigate(['/homeAdmin/main']);
          break;
      }
      return false;
    }

    
    return true;
  }

  router.navigate(['/auth']);
  return false;
};



export const loginGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);
  const userDataString = localStorage.getItem('userData');

  if (userDataString) {
    let userData;
    try {
      userData = JSON.parse(userDataString);
    } catch (error) {
      console.error('Error parsing userData from localStorage:', error);
      return true; 
    }

    if (localStorage.getItem('token')) {
      switch (userData[1]) {
        case 'PF':
          router.navigate(['/homePadres/main']);
          break;
        case 'AD':
          router.navigate(['/homeAdmin/main']);
          break;
      }
      return false;
    }
  } else {
    
    console.warn('userData not found in localStorage');
    return true; 
  }

  return true;
};

// export const authGuard: CanActivateFn = (
//   route: ActivatedRouteSnapshot,
//   state: RouterStateSnapshot
// ):
//   Observable<boolean | UrlTree>
//   | Promise<boolean | UrlTree>
//   | boolean
//   | UrlTree => {

//   return inject(AuthService)._isLoggedIn() ? true : inject(Router).createUrlTree(['/auth']);

// };
