

import 'package:flutter/material.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/utils/snackbar_util.dart';

import '../../../backend/api_requests/api_calls.dart';
import '../../../flutter_flow/flutter_flow_util.dart';
import '../../../flutter_flow/random_data_util.dart';
import '../../utils/device_util.dart';
import '../../utils/dialog_util.dart';
import '../../utils/log_util.dart';
import '../../utils/storage_util.dart';

class AuthenticationService {



  static Future<void> login(BuildContext context) async {
    final GetLocalsCall callback = PhpGroup.getLocalsCall;

    final response = await callback.call();

    if (response.jsonBody['error']) {
      DialogUtil.errorDefault(context);
      return;
    }
    List<dynamic> locals = response.jsonBody['locais'] ?? [];

    if (locals.isEmpty) {
      StorageUtil().haveLocal = false;
      context.go('/receptionPage');
    } else {
      StorageUtil().haveLocal = true;
      context.go('/homePage');
    }
    StorageUtil().isLogged = true;

  }

  static Future signIn(BuildContext context, FlutterFlowModel model, {String? emailAdress, String? password,}) async {
    try {
      final ApiCallResponse? response;
      final LoginCall callback = PhpGroup.loginCall;
      StorageUtil().deviceDescription = randomString(
        10,
        10,
        true,
        false,
        false,
      );

      final String? devUUID;
      final String userUUID;
      final String status;
      final String userDevUUID;
      final String userName;
      final String email;
      final String passwd;

      email = emailAdress!;
      passwd = password!;
      devUUID = await DeviceUtil.getDevUUID();

      if ((email != '') && (passwd != '')) {
        StorageUtil().email = email;
        StorageUtil().passwd = passwd;
        StorageUtil().devUUID = devUUID!;
        response = await callback.call();

        if (response.jsonBody['error'] == false) {
          userUUID = response.jsonBody['uid'];
          status = response.jsonBody['user']['status'];
          userDevUUID = response.jsonBody['user']['dev_id'];
          userName = response.jsonBody['user']['name'];

          StorageUtil().userUUID = userUUID;
          StorageUtil().userDevUUID = userDevUUID;
          StorageUtil().status = status;
          StorageUtil().userName = userName;

          await login(context);
        } else {
          if (response.jsonBody['error'] == null) {
            DialogUtil.errorDefault(context);
          } else {
            DialogUtil.error(
                context, response.jsonBody['error_msg'].toString());
          }
        }
      }

      return;
    } catch (e, s) {
      DialogUtil.errorDefault(context);
      LogUtil.requestAPIFailed(
          'login.php', emailAdress.toString(), "Login", e, s);
    }
  }

  static Future<bool> signUp(BuildContext context, {required String? name, String? passwd, required String? email, String? device,}) async {
    try {
      ApiCallResponse? response;
      if ((email != null && email != '') && (passwd != null && passwd != '' && passwd.length > 7) && (name != null && name != '')) {
        response = await PhpGroup.registerCall.call(
          name: name,
          password: passwd,
          email: email,
          token: randomString(36, 36, false, false, true),
          uuid: randomString(36, 36, false, false, true),
          tipo: device!,
          descricao: randomString(36, 36, true, false, false),
        );

        if (response.jsonBody['error'] == false) return true;
        DialogUtil.error(context, response.jsonBody['error_msg']);
        return false;
      } else {
        DialogUtil.errorDefault(context);
        return false;
      }
    } catch (e, s) {
      DialogUtil.errorDefault(context);
      LogUtil.requestAPIFailed('registro.php', email.toString(), "Register", e, s);
      return false;
    }
  }

  static Future<void> signOut(BuildContext context) async {
      await PhpGroup.unregisterDevice.call();
      final Map<String, dynamic> extra = <String, dynamic>{
        kTransitionInfoKey: const TransitionInfo(
          hasTransition: true,
          transitionType: PageTransitionType.scale,
          alignment: Alignment.bottomCenter,
        ),
      };
      await StorageUtil.purge();
      context.go( '/welcomePage', extra: extra);
    }

  static Future<void> forgotPassword(BuildContext context, String email) async {
    try {
      final ApiCallResponse? response;
      final ForgotPasswordCall callback = PhpGroup.forgotPasswordCall;
      final String message = FFLocalizations.of(context).getVariableText(
          enText: "Send E-mail Successful!",
          ptText: "E-mail Enviado com Sucesso!");

      response = await callback.call(email: email);

      if (response.jsonBody['error'] == false) {
        DialogUtil.success(context, message);
      } else {
        DialogUtil.error(context, response.jsonBody['error_msg']);
      }
    } catch (e, s) {
      DialogUtil.errorDefault(context);
      LogUtil.requestAPIFailed(
          'forgotPassword.php', email, "Forgot Password", e, s);
    }
  }

  static Future<void> changePassword(BuildContext context, String email, String password, String token) async {
    try {
    final ApiCallResponse response = await PhpGroup.changePasswordCall.call(email: email, psswd: password, token: token);

    if (response.jsonBody['error'] == false) {
      final String message = FFLocalizations.of(context).getVariableText(
        enText: "Password changed successfully!",
        ptText: "Senha alterada com sucesso!",
      );
      DialogUtil.success(context, message).then((_) => context.pop);
    } else {
      final String message = response.jsonBody['error_msg'];
      DialogUtil.error(context, message);
    } } catch (e, s) {
      DialogUtil.errorDefault(context);
      LogUtil.requestAPIFailed(
          'changePassword.php', email, "Change Password", e, s);
    }


  }

  static Future<void> deleteAccount(BuildContext context) async {
    String content;
    try {
      await PhpGroup.deleteAccount.call().then((value) {
        final Map<String, dynamic> extra = <String, dynamic>{
          kTransitionInfoKey: const TransitionInfo(
            hasTransition: true,
            transitionType: PageTransitionType.scale,
            alignment: Alignment.bottomCenter,
          ),
        };
        if (value.jsonBody['error'] == false) {
          content = FFLocalizations.of(context).getVariableText(
            enText: 'Account deleted successfully',
            ptText: 'Conta deletada com sucesso',
          );
          StorageUtil.purge();
          context.pop();
          context.go('/welcomePage', extra: extra);
        }
      }).catchError((err) {
        context.pop();
        content = FFLocalizations.of(context).getVariableText(
          enText: 'Error deleting account',
          ptText: 'Erro ao deletar conta',
        );
        SnackBarUtil.showSnackBar(context, content);
      });
    } catch (err) {
      context.pop();
      content = FFLocalizations.of(context).getVariableText(
        enText: 'Error deleting account',
        ptText: 'Erro ao deletar conta',
      );
      SnackBarUtil.showSnackBar(context, content, isError: true);
    }
  }

}