import 'package:flutter/material.dart';
import '../data/api_response.dart';
import '../data/session/session_storage.dart';
import '../services/login_service.dart';

enum Status { uninitialized, authenticated, authenticating, unauthenticated }

class LoginViewModel extends ChangeNotifier {
  Status _status = Status.uninitialized;
  Status get status => _status;
  bool hasErrors = false;
  Map<String, dynamic>? _errores = {};
  bool _obscureText = true;
  int? _idUsuario;
  Map<String, dynamic>? get errores => _errores;
  bool get obscureText => _obscureText;
  int? get idUsuario => _idUsuario;
  //List<String> _permisos = [];
  //List<String> get permisos => _permisos;

  String _nombre = "";
  String get nombre => _nombre;

  String _correo = "";
  String get correo => _correo;

  String _error = "";
  String get error => _error;

  Future login(String username, String password) async {
    try {
      ApiResponse apiResponse = await LoginService().logIn(username, password);
      _errores = {};
      if (apiResponse.isOk) {
        _idUsuario = apiResponse.detalle?['id'];
        String token = apiResponse.detalle?['token'];
        if (token.isNotEmpty) {
          SessionStorage().saveToken(apiResponse.detalle?['token']);
          SessionStorage().saveId(apiResponse.detalle?['id']);
          SessionStorage().saveCorreo(apiResponse.detalle!['correo']);
          SessionStorage().saveNombre(apiResponse.detalle!['nombre']);
          _status = Status.authenticated;
          notifyListeners();
        }
      }
      if (apiResponse.isError) {
        hasErrors = true;
        _errores = apiResponse.errores;
        _status = Status.unauthenticated;
        notifyListeners();
      }
    } catch (e) {
      _status = Status.unauthenticated;
      notifyListeners();
    }
  }

  void checkSession() async {
    var token = await SessionStorage().getToken();
    var id = await SessionStorage().getId();
    if (token != null && token.isNotEmpty) {
      _status = Status.authenticated;
      _idUsuario = id;
    } else {
      _status = Status.unauthenticated;
    }
    notifyListeners();
  }

  logOut() async {
    await SessionStorage().clearToken();
    _status = Status.unauthenticated;
    notifyListeners();
  }

  void showPassword() {
    _obscureText = !_obscureText;
    notifyListeners();
  }

  setValores() async {
    _nombre = (await SessionStorage().getNombre()).toString();
    _correo = (await SessionStorage().getCorreo()).toString();
    notifyListeners();
  }

  bool validarEmail(String email) =>
      RegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
          .hasMatch(email.trim());
}
