import 'package:flutter/material.dart';
import 'package:hub/backend/api_requests/api_calls.dart';
import 'package:hub/components/templates_components/change_passs_qr_code_pass_key_template_component/change_pass_widget.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/helpers/secure_storage_helper.dart';
import 'package:hub/shared/helpers/sqlite_storage_helper.dart';
import 'package:hub/shared/services/authentication/authentication_service.dart';
import 'package:hub/shared/services/localization/localization_service.dart';
import 'package:hub/shared/utils/storage_util.dart';
import 'package:share_plus/share_plus.dart';

import '../../shared/utils/snackbar_util.dart';

class PreferencesPageModel with ChangeNotifier {
  final unfocusNode = FocusNode();

  PreferencesPageModel() {
    initVariables();
  }

  Future<void> initVariables() async {
    notifyListeners();
  }

  Future<void> enablePerson(BuildContext context) async {
    final String userDevUUID = StorageUtil().userDevUUID;
    notifyListeners();
    Share.share(
      FFLocalizations.of(context).getVariableText(
        ptText: 'Este é o meu identificador de acesso: $userDevUUID',
        enText: 'This is my access identifier: $userDevUUID',
      ),
    );
  }

  Future<void> toggleNotify(BuildContext context) async {
    final String title = FFLocalizations.of(context).getVariableText(
      enText: 'Change notification',
      ptText: 'Alterar notificação',
    );
    final String content = FFLocalizations.of(context).getVariableText(
      enText: 'Are you sure you want to change your notification?',
      ptText: 'Tem certeza que deseja alterar sua notificação?',
    );
    onConfirm() async {
      String content;
      try {
        content = FFLocalizations.of(context).getVariableText(
          enText: 'Notification changed successfully',
          ptText: 'Notificação alterada com sucesso',
        );
        context.pop();
        SnackBarUtil.showSnackBar(context, content);
        StorageUtil().notify = !StorageUtil().notify;
        notifyListeners();
      } catch (err) {
        content = FFLocalizations.of(context).getVariableText(
          enText: 'Error changing notification',
          ptText: 'Erro ao alterar notificação',
        );
        context.pop();
        SnackBarUtil.showSnackBar(context, content, isError: true);
      }
    }

    showAlertDialog(context, title, content, onConfirm);
  }

  Future<void> toggleAccess(BuildContext context) async {
    onChange(String key) async {
      StorageUtil().accessPass = key;
      await PhpGroup.changePass
          .call(
        newSenha: key,
      )
          .then((value) async {
        final String content;
        if (jsonDecode(value.jsonBody['error'].toString()) == false) {
          if (!StorageUtil().access) StorageUtil().access = !StorageUtil().access;
          notifyListeners();
          content = FFLocalizations.of(context).getVariableText(
            enText: 'Access pass changed successfully',
            ptText: 'Senha de acesso alterada com sucesso',
          );
          SnackBarUtil.showSnackBar(context, content);
        } else {
          content = FFLocalizations.of(context).getVariableText(
            ptText: 'Erro ao alterar senha de acesso',
            enText: 'Error changing access pass',
          );
          SnackBarUtil.showSnackBar(context, content, isError: true);
        }
      }).catchError((e, s) {
        final String content = FFLocalizations.of(context).getVariableText(
          ptText: 'Erro ao alterar senha de acesso',
          enText: 'Error changing access pass',
        );
        SnackBarUtil.showSnackBar(context, content, isError: true);
      }).whenComplete(() => notifyListeners());
    }

    _showPassKey(context, onChange);
  }

  Future<void> togglePanic(BuildContext context) async {
    onChange(String key) async {
      StorageUtil().panicPass = key;
      await PhpGroup.changePanic
          .call(
        newSenhaPanico: StorageUtil().panicPass,
      )
          .then((value) async {
        final String content;
        if (jsonDecode(value.jsonBody['error'].toString()) == false) {
          if (!StorageUtil().panic) StorageUtil().panic = !StorageUtil().panic;
          notifyListeners();
          content = FFLocalizations.of(context).getVariableText(
            enText: 'Panic password changed successfully',
            ptText: 'Senha de pânico alterada com sucesso',
          );
          SnackBarUtil.showSnackBar(context, content);
        } else {
          content = FFLocalizations.of(context).getVariableText(
            ptText: 'Erro ao alterar senha de pânico',
            enText: 'Error changing panic password',
          );
          SnackBarUtil.showSnackBar(context, content, isError: true);
        }
      }).catchError((e, s) {
        final String content = FFLocalizations.of(context).getVariableText(
          ptText: 'Erro ao alterar senha de pânico',
          enText: 'Error changing panic password',
        );
        SnackBarUtil.showSnackBar(context, content, isError: true);
      }).whenComplete(() => notifyListeners());
    }

    _showPassKey(context, onChange);
  }

  Future<void> toggleFingerprint(BuildContext context) async {
    final String content = FFLocalizations.of(context).getVariableText(
      enText: 'Fingerprint changed successfully',
      ptText: 'Impressão digital alterada com sucesso',
    );

    onChange(String? key) async {
      StorageUtil().fingerprint = !StorageUtil().fingerprint;
      if (!StorageUtil().fingerprint) StorageUtil().fingerprintPass = key ?? '';
      if (StorageUtil().fingerprint) StorageUtil().fingerprintPass = '';

      notifyListeners();

      SnackBarUtil.showSnackBar(context, content);
    }

    StorageUtil().fingerprint ? onChange(null) : _showPassKey(context, onChange);
  }

  Future<void> deleteAccount(BuildContext context) async {
    final String title = FFLocalizations.of(context).getVariableText(
      enText: 'Delete account',
      ptText: 'Deletar conta',
    );
    final String content = FFLocalizations.of(context).getVariableText(
      enText: 'Are you sure you want to delete your account?',
      ptText: 'Tem certeza que deseja deletar sua conta?',
    );
    onConfirm() async => AuthenticationService.deleteAccount(context);

    showAlertDialog(context, title, content, onConfirm);
  }

  void logout(BuildContext context) async {
    final String title = FFLocalizations.of(context).getVariableText(
      enText: 'Logout',
      ptText: 'Sair',
    );
    final String content = FFLocalizations.of(context).getVariableText(
      enText: 'Are you sure you want to logout?',
      ptText: 'Tem certeza que deseja sair?',
    );
    onConfirm() async => AuthenticationService.signOut(context);

    showAlertDialog(context, title, content, onConfirm);
  }

  void localUnlink(BuildContext context) {
    final String title = FFLocalizations.of(context).getVariableText(
      enText: 'Unlink device',
      ptText: 'Desvincular dispositivo',
    );
    final String content = FFLocalizations.of(context).getVariableText(
      enText: 'Are you sure you want to unlink your device?',
      ptText: 'Tem certeza que deseja desvincular seu dispositivo?',
    );
    onConfirm() async => LocalizationService.unlinkLocal(context);

    showAlertDialog(context, title, content, onConfirm);
  }








  void _showPassKey(BuildContext context, void Function(String) onChange) async {
    await showModalBottomSheet(
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      useSafeArea: true,
      context: context,
      builder: (context) {
        return Padding(
          padding: MediaQuery.viewInsetsOf(context),
          child: PassKeyTemplateWidget(
            toggleActionStatus: (key) async {
              onChange.call(key);
            },
          ),
        );
      },
    ).catchError((err, stack) {
      final String content = FFLocalizations.of(context).getVariableText(
        enText: 'Error changing key',
        ptText: 'Erro ao alterar senha',
      );
      SnackBarUtil.showSnackBar(context, content, isError: true);
    }).whenComplete(() => notifyListeners());
  }

}
