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;
  String? _idUsuario;
  Map<String, dynamic>? get errores => _errores;
  bool get obscureText => _obscureText;
  String? get idUsuario => _idUsuario;
  List<String> _permisos = [];
  List<String> get permisos => _permisos;

  String name = "";
  String get _name => name;

  String email = "";
  String get _email => email;

  String _empresa = "";
  String get empresa => _empresa;

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

  bool _cargando = false;
  bool get cargando => _cargando;

  setCargando(bool value) {
    _cargando = value;
    notifyListeners();
  }

  Future login(String username, String password) async {
    _cargando = true;
    notifyListeners();
    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!['email']);
          SessionStorage().saveNombre(apiResponse.detalle!['name']);
          _status = Status.authenticated;
          _cargando = false;
          notifyListeners();
          return _status;
        }
      }
      if (apiResponse.isError) {
        hasErrors = true;
        _errores = apiResponse.errores;
        _status = Status.unauthenticated;
        _cargando = false;
        notifyListeners();
      }
    } catch (e) {
      _status = Status.unauthenticated;
      _cargando = false;
      notifyListeners();
    }
  }

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

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

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

  setValores() async {
    name = (await SessionStorage().getNombre()).toString();
    email = (await SessionStorage().getCorreo()).toString();
    _empresa = (await SessionStorage().getEmpresa()).toString();
    notifyListeners();
  }

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