import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:hub/features/backend/index.dart';
import 'package:hub/features/local/index.dart';
import 'package:hub/features/module/data/repositories/license_repository_impl.dart';
import 'package:hub/features/storage/index.dart';
import 'package:hub/flutter_flow/internationalization.dart';
import 'package:hub/shared/utils/dialog_util.dart';
import 'package:hub/shared/utils/log_util.dart';

class LocalUtil {
  static void handleError(BuildContext context, String errorMsg) async {
    final String devUUID =
        await StorageHelper().get(ProfileStorageKey.devUUID.key) ?? '';
    final String userUUID =
        await StorageHelper().get(ProfileStorageKey.userUUID.key) ?? '';
    final bool isAuthenticated = userUUID.isNotEmpty && devUUID.isNotEmpty;
    final bool isDevLinked =
        !errorMsg.contains('Esse dispositivo nao pertence a esse usuario');
    log('() => isLinked: $errorMsg');
    if (!isAuthenticated) {
      errorMsg = FFLocalizations.of(context).getVariableText(
        ptText: 'Erro ao obter credenciais de autenticação',
        enText: 'Error getting authentication credentials',
      );
      await DialogUtil.error(context, errorMsg);
      return;
      // await DialogUtil.error(context, errorMsg).whenComplete(() async => await AuthenticationService.signOut(context));
    }
    if (!isDevLinked) {
      errorMsg = FFLocalizations.of(context).getVariableText(
        ptText: 'Não foi possível vincular o dispositivo, tente novamente.',
        enText: 'Unable to link device, try again',
      );
      await DialogUtil.warning(context, errorMsg);
      return;
    }
    // await DialogUtil.error(context, errorMsg).whenComplete(() async => await LocalsRemoteDataSourceImpl().selectLocal(context, null));
  }

  static Future<bool> handleUnavailable(
      BuildContext context, List<dynamic> locals) async {
    log('() => isUnavailable');
    try {
      await StorageHelper()
          .set(ProfileStorageKey.clientUUID.key, locals[0]['CLI_ID']);
      await StorageHelper()
          .set(ProfileStorageKey.ownerUUID.key, locals[0]['CLU_OWNER_ID']);
      await StorageHelper()
          .set(ProfileStorageKey.clientName.key, locals[0]['CLI_NOME']);
      await StorageHelper()
          .set(ProfileStorageKey.ownerName.key, locals[0]['CLU_OWNER_DSC']);

      var response = await PhpGroup.resopndeVinculo.call(tarefa: 'A');
      if (response.jsonBody['error'] == true) {
        await StorageHelper().set(ProfileStorageKey.clientUUID.key, '');
        await StorageHelper().set(ProfileStorageKey.ownerUUID.key, '');
        await StorageHelper().set(ProfileStorageKey.clientName.key, '');
        await StorageHelper().set(ProfileStorageKey.ownerName.key, '');

        return false;
      }
      if (response.jsonBody['error'] == false)
        return await LocalsRemoteDataSourceImpl()
            .processProperty(context)
            .then((value) => value);
    } catch (e, s) {
      await DialogUtil.errorDefault(context);
      LogUtil.requestAPIFailed(
          'responderVinculo.php', '', 'Responder Vínculo', e, s);
      return false;
    }
    return false;
  }

  static Future<bool> handleEnabled(BuildContext context, dynamic local) async {
    log('() => isEnabled');
    await StorageHelper()
        .set(ProfileStorageKey.clientUUID.key, local['CLI_ID']);
    await StorageHelper()
        .set(ProfileStorageKey.ownerUUID.key, local['CLU_OWNER_ID']);
    await StorageHelper()
        .set(ProfileStorageKey.clientName.key, local['CLI_NOME']);
    await StorageHelper()
        .set(ProfileStorageKey.ownerName.key, local['CLU_OWNER_DSC']);
    await StorageHelper()
        .set(ProfileStorageKey.userName.key, local['USU_NOME']);
    return await LocalsRemoteDataSourceImpl()
        .processProperty(context)
        .then((v) async {
      if (v == true) return await LicenseRepositoryImpl().updateLicense();
      return v;
    });
  }

  static void logLocalsStatus(List<dynamic> locals) {
    for (var local in locals) {
      final String status = local['CLU_STATUS'];
      log('() => CLU_STATUS: $status');
    }
  }

  static bool _processSystemOption(String? json) {
    if (json == null) return false;
    if (json == 'S')
      return true;
    else
      return false;
  }

  static Future<bool> updateStorageUtil(Map<String, dynamic> jsonBody) async {
    try {
      await StorageHelper()
          .set(LocalsStorageKey.whatsapp.key, jsonBody['whatsapp'] ?? false);
      await StorageHelper().set(
          LocalsStorageKey.provisional.key, jsonBody['provisional'] ?? false);
      await StorageHelper().set(
        LocalsStorageKey.pets.key,
        jsonBody['pet'] ?? false,
      );
      await StorageHelper().set(
        LocalsStorageKey.notify.key,
        _processSystemOption(
          jsonBody['visitado']['VDO_NOTTERCEIROS'],
        ),
      );
      if (jsonBody['visitado']['VDO_TEM_SENHA_ACESSO'] != null) {
        await StorageHelper().set(
          LocalsStorageKey.access.key,
          _processSystemOption(jsonBody['visitado']['VDO_TEM_SENHA_ACESSO']),
        );
        await StorageHelper().set(
          LocalsStorageKey.panic.key,
          _processSystemOption(jsonBody['visitado']['VDO_TEM_SENHA_PANICO']),
        );
      }

      await StorageHelper().set(
          LocalsStorageKey.petAmount.key,
          jsonBody['petAmountRegister']?.toString().isEmpty ?? true
              ? '0'
              : jsonBody['petAmountRegister'].toString());
      await StorageHelper().set(ProfileStorageKey.userName.key,
          jsonBody['visitado']['VDO_NOME'] ?? '');
      await StorageHelper().set(ProfileStorageKey.userEmail.key,
          jsonBody['visitado']['VDO_EMAIL'] ?? '');
      await StorageHelper().set(
          LocalsStorageKey.provisional.key, jsonBody['provisional'] ?? false);

      final bool isNewVersion = jsonBody['newVersion'] ?? false;
      await StorageHelper()
          .set(LocalsStorageKey.isNewVersion.key, isNewVersion);
      return isNewVersion;
    } catch (e, s) {
      log('Error in _updateStorageUtil: $e', stackTrace: s);
      return false;
    }
  }

  static bool isActive(List<dynamic> locals) {
    return locals.where((local) => local['CLU_STATUS'] == 'A').isNotEmpty;
  }

  static Future<bool> isInactived(List<dynamic> locals) async {
    String cliUUID =
        (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
    return locals
        .where(
            (local) => local['CLI_ID'] != cliUUID && local['CLU_STATUS'] == 'A')
        .isNotEmpty;
  }

  static bool isPending(List<dynamic> locals) {
    return locals
        .where(
            (local) => local['CLU_STATUS'] != 'B' && local['CLU_STATUS'] != 'A')
        .isNotEmpty;
  }

  static Future<bool> isUnselected() async {
    String cliUUID =
        (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
    String cliName =
        (await StorageHelper().get(ProfileStorageKey.clientName.key)) ?? '';
    String ownerUUID =
        (await StorageHelper().get(ProfileStorageKey.ownerUUID.key)) ?? '';
    return cliUUID.isEmpty && cliName.isEmpty && ownerUUID.isEmpty;
  }

  static Future<bool> isSelected(bool isInactived) async {
    String cliUUID =
        (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
    String cliName =
        (await StorageHelper().get(ProfileStorageKey.clientName.key)) ?? '';
    return cliUUID.isNotEmpty && cliName.isNotEmpty && isInactived;
  }

  static Future<bool> isAvailable() async {
    String cliUUID =
        (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
    String cliName =
        (await StorageHelper().get(ProfileStorageKey.clientName.key)) ?? '';
    return cliUUID.isNotEmpty && cliName.isNotEmpty;
  }
}
