import 'dart:developer';

import 'package:hub/app_state.dart';
import 'package:hub/backend/api_requests/api_calls.dart';

import 'package:flutter/material.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_icon_button.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:share_plus/share_plus.dart';

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

  Future<void> toggleFingerprint(BuildContext context) async {
    // FFAppState().checkBiometrics()
    // .then((value) => FFAppState().authenticateBiometric()
    //   .then( (value) {
    //     FFAppState().fingerprint = !FFAppState().fingerprint;

    //     })
    //   .whenComplete(() => notifyListeners()));

    if (FFAppState().fingerprint) {
      FFAppState().fingerprint = false;
      FFAppState().deleteFingerprintPass();
      notifyListeners();
    } else {
      await showModalBottomSheet(
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        useSafeArea: true,
        context: context,
        builder: (context) {
          return Padding(
            padding: MediaQuery.viewInsetsOf(context),
            child: PassKeyTemplateWidget(
              toggleActionStatus: (key) async {
                log(key);
                FFAppState().fingerprintPass = key;
                FFAppState().fingerprint = true;
              },
            ),
          );
        },
      ).whenComplete(() => notifyListeners());
    }
  }

  void enablePerson(BuildContext context) {
    notifyListeners();
    Share.share(
      FFLocalizations.of(context).getVariableText(
        ptText:
            'Este é o meu identificador de acesse: ${FFAppState().userDevUUID}',
        enText: 'This is my access identifier: ${FFAppState().userDevUUID}',
      ),
    );
  }

  void toggleNotify(BuildContext context) {
    FFAppState().notify = !FFAppState().notify;
    PhpGroup.changeNotifica
        .call(
      userUUID: FFAppState().userUUID,
      devUUID: FFAppState().devUUID,
      cliID: FFAppState().cliUUID,
      atividade: 'updVisitado',
      notifica: FFAppState().notify ? 'S' : 'N',
    )
        .catchError((err) {
      log(err.toString());
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
              FFLocalizations.of(context).getVariableText(
                enText: 'Error changing notification',
                ptText: 'Erro ao alterar notificação',
              ),
              style: TextStyle(color: FlutterFlowTheme.of(context).info)),
          backgroundColor: FlutterFlowTheme.of(context).error,
          duration: const Duration(seconds: 3),
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
        ),
      );
    });
    notifyListeners();
  }

  void localUnlink(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
            title: Text(
              FFLocalizations.of(context).getVariableText(
                enText: 'Unlink device',
                ptText: 'Desvincular dispositivo',
              ),
            ),
            content: Text(
              FFLocalizations.of(context).getVariableText(
                enText: 'Are you sure you want to unlink this device?',
                ptText: 'Tem certeza que deseja desvincular este dispositivo?',
              ),
            ),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text(
                  FFLocalizations.of(context).getVariableText(
                    enText: 'Cancel',
                    ptText: 'Cancelar',
                  ),
                  style: TextStyle(color: FlutterFlowTheme.of(context).info),
                ),
              ),
              TextButton(
                onPressed: () {
                  PhpGroup.resopndeVinculo
                      .call(
                    userUUID: FFAppState().userUUID,
                    devUUID: FFAppState().devUUID,
                    cliID: FFAppState().cliUUID,
                    tarefa: 'I',
                  )
                      .catchError((err) {
                    log(err.toString());
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text(
                            FFLocalizations.of(context).getVariableText(
                              enText: 'Error unlinking device',
                              ptText: 'Erro ao desvincular dispositivo',
                            ),
                            style: TextStyle(
                                color: FlutterFlowTheme.of(context).info)),
                        backgroundColor: FlutterFlowTheme.of(context).error,
                        duration: const Duration(seconds: 3),
                        behavior: SnackBarBehavior.floating,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                      ),
                    );
                  }).then(
                    (value) {
                      FFAppState().deleteCliUUID();
                      FFAppState().deleteLocal();
                      FFAppState().deleteOwnerUUID();
                      Navigator.pop(context);
                      Navigator.pop(context);
                    },
                  );
                  notifyListeners();
                },
                child: Text(
                  FFLocalizations.of(context).getVariableText(
                    enText: 'Unlink',
                    ptText: 'Desvincular',
                  ),
                  style: TextStyle(color: FlutterFlowTheme.of(context).info),
                ),
              ),
            ],
          );
        });
    notifyListeners();
  }

  void deleteAccount(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
            title: Text(
              FFLocalizations.of(context).getVariableText(
                enText: 'Delete account',
                ptText: 'Deletar conta',
              ),
            ),
            content: Text(
              FFLocalizations.of(context).getVariableText(
                enText: 'Are you sure you want to delete your account?',
                ptText: 'Tem certeza que deseja deletar sua conta?',
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: Text(
                  FFLocalizations.of(context).getVariableText(
                    enText: 'Cancel',
                    ptText: 'Cancelar',
                  ),
                  style: TextStyle(color: FlutterFlowTheme.of(context).info),
                ),
              ),
              TextButton(
                onPressed: () {
                  PhpGroup.deleteAccount
                      .call(
                    devUUID: FFAppState().devUUID,
                    userUUID: FFAppState().userUUID,
                  )
                      .then((value) {
                    FFAppState().deleteAll();
                    FFAppState().isLogged = false;
                    context.goNamed(
                      'welcomePage',
                      extra: <String, dynamic>{
                        kTransitionInfoKey: const TransitionInfo(
                          hasTransition: true,
                          transitionType: PageTransitionType.scale,
                          alignment: Alignment.bottomCenter,
                        ),
                      },
                    );
                  }).catchError((err) {
                    log(err.toString());
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text(
                            FFLocalizations.of(context).getVariableText(
                              enText: 'Error deleting account',
                              ptText: 'Erro ao deletar conta',
                            ),
                            style: TextStyle(
                                color: FlutterFlowTheme.of(context).info)),
                        backgroundColor: FlutterFlowTheme.of(context).error,
                        duration: const Duration(seconds: 3),
                        behavior: SnackBarBehavior.floating,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                      ),
                    );
                  });
                  notifyListeners();
                },
                child: Text(
                  FFLocalizations.of(context).getVariableText(
                    enText: 'Delete',
                    ptText: 'Deletar',
                  ),
                  style: TextStyle(color: FlutterFlowTheme.of(context).info),
                ),
              ),
            ],
          );
        });
    notifyListeners();

    // PhpGroup.deleteAccount
    //     .call(
    //   devUUID: FFAppState().devUUID,
    //   userUUID: FFAppState().userUUID,
    // )
    //     .then((value) {
    //   FFAppState().deleteAll();
    //   FFAppState().isLogged = false;
    //   context.goNamed(
    //     'welcomePage',
    //     extra: <String, dynamic>{
    //       kTransitionInfoKey: const TransitionInfo(
    //         hasTransition: true,
    //         transitionType: PageTransitionType.scale,
    //         alignment: Alignment.bottomCenter,
    //       ),
    //     },
    //   );
    // }).catchError((err) {
    //   log(err.toString());
    //   ScaffoldMessenger.of(context).showSnackBar(
    //     SnackBar(
    //       content: Text(
    //           FFLocalizations.of(context).getVariableText(
    //             ptText: 'Erro ao deletar dispositivo',
    //             enText: 'Error deleting device',
    //           ),
    //           style: TextStyle(color: FlutterFlowTheme.of(context).info)),
    //       backgroundColor: FlutterFlowTheme.of(context).error,
    //       duration: const Duration(seconds: 3),
    //       behavior: SnackBarBehavior.floating,
    //       shape: RoundedRectangleBorder(
    //         borderRadius: BorderRadius.circular(30),
    //       ),
    //     ),
    //   );
    // });
  }

  Future<void> togglePass(BuildContext context) async {
    debugPrint('pass: ${FFAppState().pass}');
    // if (FFAppState().pass) {
    //   FFAppState().pass = false;
    //   FFAppState().deleteAccessPass();
    //   notifyListeners();
    // } else {
    await showModalBottomSheet(
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      useSafeArea: true,
      context: context,
      builder: (context) {
        return Padding(
          padding: MediaQuery.viewInsetsOf(context),
          child: PassKeyTemplateWidget(
            toggleActionStatus: (key) async {
              FFAppState().accessPass = key;
              notifyListeners();
              debugPrint('key: $key');
              await PhpGroup.changePass
                  .call(
                userUUID: FFAppState().userUUID,
                devUUID: FFAppState().devUUID,
                cliID: FFAppState().cliUUID,
                atividade: 'updVisitado',
                newSenha: FFAppState().accessPass,
              )
                  .then((value) {
                FFAppState().pass = true;
                // var error = jsonDecode(value.jsonBody['error'].toString());
                // log('${jsonDecode(value.jsonBody['error'].toString())}');
                if (jsonDecode(value.jsonBody['error'].toString()) == false) {
                  FFAppState().pass = true;
                } else {
                  FFAppState().pass = false;
                }
              }).catchError((error, StackTrace) {
                FFAppState().pass = false;
                log(error.toString());
                log(StackTrace.toString());
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text(
                        FFLocalizations.of(context).getVariableText(
                          ptText: 'Erro ao alterar senha de acesso',
                          enText: 'Error changing access password',
                        ),
                        style: TextStyle(
                            color: FlutterFlowTheme.of(context).info)),
                    backgroundColor: FlutterFlowTheme.of(context).error,
                    duration: const Duration(seconds: 3),
                    behavior: SnackBarBehavior.floating,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                  ),
                );
              }).whenComplete(() => notifyListeners());
            },
          ),
        );
      },
    );
    // }
  }

  Future<void> togglePanic(BuildContext context) 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 {
              FFAppState().panicPass = key;
              notifyListeners();
              await PhpGroup.changePanic
                  .call(
                userUUID: FFAppState().userUUID,
                devUUID: FFAppState().devUUID,
                cliID: FFAppState().cliUUID,
                atividade: 'updVisitado',
                newSenhaPanico: FFAppState().panicPass,
              )
                  .then((value) {
                FFAppState().panic = true;
                if (jsonDecode(value.jsonBody['error'].toString()) == false) {
                  FFAppState().panic = true;
                } else {
                  FFAppState().panic = false;
                }
              }).catchError((e, s) {
                FFAppState().panic = false;

                log(e.toString());
                log(s.toString());
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text(
                        FFLocalizations.of(context).getVariableText(
                          ptText: 'Erro ao alterar senha de pânico',
                          enText: 'Error changing panic password',
                        ),
                        style: TextStyle(
                            color: FlutterFlowTheme.of(context).info)),
                    backgroundColor: FlutterFlowTheme.of(context).error,
                    duration: const Duration(seconds: 3),
                    behavior: SnackBarBehavior.floating,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                  ),
                );
              }).whenComplete(() => notifyListeners());
            },
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    unfocusNode.dispose();
    super.dispose();
  }
}
