import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:hub/components/templates_components/details_component/details_component_widget.dart';
import 'package:hub/components/templates_components/message_notificaion_modal_template_component/message_notification_widget.dart';
import 'package:hub/features/backend/index.dart';
import 'package:hub/features/storage/index.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:hub/shared/utils/dialog_util.dart';

Future<void> onMessageReceived(
    Map<String, dynamic> payload, String? extra, String? handleClick) async {
  final localId = jsonDecode(payload['local']!)['CLI_ID'];

  final cliUUID =
      (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';

  answersRequest(
      {required BuildContext context,
      required String? ref,
      required String? task,
      required String? response,
      required String? id}) async {
    final ApiCallResponse? respondeSolicitacaoCall;
    final RespondeSolicitacaoCall callback = PhpGroup.respondeSolicitacaoCall;

    respondeSolicitacaoCall = await callback.call(
      referencia: ref,
      tarefa: task,
      resposta: response,
      idVisitante: id,
    );

    if (respondeSolicitacaoCall.statusCode == 200) {
      return !respondeSolicitacaoCall.jsonBody['error'];
    } else {
      return false;
    }
  }

  switch (handleClick) {
    case 'visit_request':
      showDialog(
          context: navigatorKey.currentContext!,
          barrierColor: Colors.transparent,
          barrierDismissible: true,
          builder: (BuildContext context) {
            return Dialog(
              child: SizedBox(
                width: MediaQuery.of(context).size.width * 0.8,
                height: MediaQuery.of(context).size.height * 0.6,
                child: DetailsComponentWidget(
                  buttons: [
                    FlutterFlowIconButton(
                      icon: const Icon(Icons.done),
                      onPressed: () async {
                        showAlertDialog(
                          context,
                          FFLocalizations.of(context).getVariableText(
                            ptText: 'Aprovar Visita',
                            enText: 'Approve Visit',
                          ),
                          FFLocalizations.of(context).getVariableText(
                            ptText:
                                'Você tem certeza que deseja aprovar essa visita?',
                            enText:
                                'Are you sure you want to approve this visit?',
                          ),
                          () async {
                            await answersRequest(
                              context: context,
                              ref: payload['referencia'].toString(),
                              task: 'L',
                              response: '',
                              id: payload['idVisitante'].toString(),
                            ).then((value) async {
                              if (value) {
                                context.pop();
                                context.pop();
                              } else {
                                context.pop();
                                context.pop();
                                await DialogUtil.errorDefault(context);
                              }
                            }).catchError((e) async {
                              context.pop();
                              context.pop();
                              await DialogUtil.errorDefault(context);
                            });
                          },
                        );
                      },
                    ),
                    FlutterFlowIconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () async {
                        showAlertDialog(
                            context,
                            FFLocalizations.of(context).getVariableText(
                              ptText: 'Bloquear Visita',
                              enText: 'Block Visit',
                            ),
                            FFLocalizations.of(context).getVariableText(
                              ptText:
                                  'Você tem certeza que deseja bloquear essa visita?',
                              enText:
                                  'Are you sure you want to block this visit?',
                            ), () async {
                          await answersRequest
                              .call(
                            context: context,
                            ref: payload['referencia'].toString(),
                            task: 'B',
                            response: '',
                            id: payload['idVisitante'].toString(),
                          )
                              .then((value) async {
                            if (value) {
                              context.pop();
                              context.pop();
                            } else {
                              context.pop();
                              context.pop();
                              await DialogUtil.errorDefault(context);
                            }
                          }).catchError((e) async {
                            context.pop();
                            context.pop();
                            await DialogUtil.errorDefault(context);
                          });
                        });
                      },
                    ),
                  ],
                  labelsHashMap: Map<String, String>.from({
                    FFLocalizations.of(context).getVariableText(
                      enText: 'Visitor',
                      ptText: 'Visitante',
                    ): payload['nomevisita'],
                    FFLocalizations.of(context).getVariableText(
                      enText: 'Reason',
                      ptText: 'Motivo',
                    ): payload['motivo'],
                    FFLocalizations.of(context).getVariableText(
                      enText: 'Message',
                      ptText: 'Mensagem',
                    ): payload['mensagem'],
                  }),
                  imagePath:
                      'https://freaccess.com.br/freaccess/getImage.php?cliID=$cliUUID&atividade=getFoto&Documento=${payload['documento'] ?? ''}&tipo=E',
                  statusHashMap: [
                    {
                      FFLocalizations.of(context).getVariableText(
                        enText: 'Active',
                        ptText: 'Ativo',
                      ): FlutterFlowTheme.of(context).warning,
                    },
                  ],
                ),
              ),
            );
          });

      break;
    case 'access':
      showDialog(
          context: navigatorKey.currentContext!,
          barrierColor: Colors.transparent,
          barrierDismissible: true,
          builder: (BuildContext context) {
            var id = payload['USR_TIPO'].toString() == 'O'
                ? payload['USR_ID'].toString() == ''
                    ? '0'
                    : payload['USR_ID'].toString()
                : payload['USR_DOCUMENTO'].toString() == ''
                    ? '0'
                    : payload['USR_DOCUMENTO'].toString();
            var type = payload['USR_TIPO'];
            return Dialog(
              backgroundColor: Colors.transparent,
              child: DetailsComponentWidget(
                imagePath:
                    'https://freaccess.com.br/freaccess/getImage.php?cliID=$cliUUID&atividade=getFoto&Documento=$id&tipo=$type',
                labelsHashMap: Map<String, String>.from({
                  FFLocalizations.of(context).getVariableText(
                    enText: 'Name',
                    ptText: 'Nome',
                  ): payload['PES_NOME'] != null
                      ? payload['PES_NOME'].toString()
                      : payload['USR_NOME'].toString(),
                  FFLocalizations.of(context).getVariableText(
                    enText: 'Type',
                    ptText: 'Tipo',
                  ): payload['USR_TIPO'].toString() == 'O'
                      ? 'Morador'
                      : 'Visitante',
                  FFLocalizations.of(context).getVariableText(
                    enText: 'Access Date',
                    ptText: 'Data de Acesso',
                  ): payload['ACE_DATAHORA'].toString(),
                  FFLocalizations.of(context).getVariableText(
                    ptText: 'Setor',
                    enText: 'Sector',
                  ): payload['SET_DESCRICAO'].toString(),
                }),
                statusHashMap: [
                  {
                    if (payload['ACE_TIPO'].toString() == '0')
                      FFLocalizations.of(context).getVariableText(
                        enText: 'Entrance',
                        ptText: 'Entrada',
                      ): FlutterFlowTheme.of(context).success,
                    if (payload['ACE_TIPO'].toString() == '1')
                      FFLocalizations.of(context).getVariableText(
                        enText: 'Exit',
                        ptText: 'Saída',
                      ): FlutterFlowTheme.of(context).success
                  }
                ],
                // onTapCardItemAction: () {},
                buttons: const [],
              ),
            );
          });
      break;
    case 'mensagem':
      showDialog(
          context: navigatorKey.currentContext!,
          barrierColor: Colors.transparent,
          barrierDismissible: true,
          builder: (BuildContext context) {
            return Dialog(
              child: SizedBox(
                width: MediaQuery.of(context).size.width * 0.3,
                height: MediaQuery.of(context).size.height * 0.3,
                child: MessageNotificationModalTemplateComponentWidget(
                  id: localId,
                  from: payload['remetente'].toString(),
                  to: payload['destinatario'].toString() == 'O'
                      ? 'Morador'
                      : 'Visitante',
                  message:
                      extra.toString().isEmpty ? 'Unknown' : extra.toString(),
                ),
              ),
            );
          });

      break;
    case 'enroll_cond':
      await StorageHelper().set(SecureStorageKey.haveLocal.value, true);
      navigatorKey.currentContext!.go('/homePage');
      break;
    default:
      break;
  }
}

class NotificationService {
  static Future<void> initialize([bool forceRequest = true]) async {
    await AwesomeNotifications().initialize(
        'resource://drawable/notification_icon',
        [
          NotificationChannel(
            channelKey: 'basic_channel',
            channelGroupKey: 'basic_channel',
            channelName: 'Notificações do App',
            channelDescription: 'Canal de notificação do Aplicativo',
            importance: NotificationImportance.Max,
            channelShowBadge: false,
            playSound: true,
            criticalAlerts: true,
            onlyAlertOnce: true,
            defaultColor: Colors.green,
            ledColor: Colors.white,
          )
        ],
        channelGroups: [
          NotificationChannelGroup(
              channelGroupKey: 'basic_channel_group',
              channelGroupName: 'group_1')
        ],
        debug: kDebugMode);

    await AwesomeNotifications()
        .isNotificationAllowed()
        .then((isAllowed) async {
      final bool requestOSnotification = (await StorageHelper()
              .get(LocalsStorageKey.requestOSNotification.key)) ==
          'true';

      if (requestOSnotification == false) {
        if (isAllowed == false) {
          await StorageHelper()
              .set(LocalsStorageKey.requestOSNotification.key, true);
          if (forceRequest == true)
            await AwesomeNotifications().requestPermissionToSendNotifications();
        }
      }
      return;
    });

    await AwesomeNotifications().setListeners(
        onActionReceivedMethod: onActionReceivedMethod,
        onNotificationCreatedMethod: onNotificationCreatedMethod,
        onNotificationDisplayedMethod: onNotificationDisplayedMethod,
        onDismissActionReceivedMethod: onDismissActionReceivedMethod);
  }

  static Future<void> onActionReceivedMethod(
      ReceivedAction receivedAction) async {
    final payload = receivedAction.payload ?? {};
    final extra = receivedAction.body;
    final handleClick = payload['click_action'];
    onMessageReceived(payload, extra, handleClick);
  }

  static Future<void> onNotificationCreatedMethod(
      ReceivedNotification receivedNotification) async {}

  static Future<void> onNotificationDisplayedMethod(
      ReceivedNotification receivedNotification) async {}

  static Future<void> onDismissActionReceivedMethod(
      ReceivedAction receivedAction) async {}

  static Future<void> show({
    required final String title,
    required final String body,
    final String? summary,
    final Map<String, String>? payload,
    final ActionType actionType = ActionType.Default,
    final NotificationLayout notificationLayout = NotificationLayout.Default,
    final NotificationCategory? category,
    final String? bigPicture,
    final List<NotificationActionButton>? actionButtons,
    final bool scheduled = false,
    final int? interval,
  }) async {
    assert(!scheduled || (scheduled && interval != null));
    await AwesomeNotifications().createNotification(
        content: NotificationContent(
          id: 0,
          channelKey: 'basic_channel',
          title: title,
          body: body,
          actionType: actionType,
          notificationLayout: notificationLayout,
          summary: summary,
          category: category,
          payload: payload,
          bigPicture: bigPicture,
          badge: 0,
        ),
        actionButtons: actionButtons,
        schedule: scheduled
            ? NotificationInterval(
                interval: Duration(seconds: interval!),
                timeZone:
                    await AwesomeNotifications().getLocalTimeZoneIdentifier(),
                preciseAlarm: true)
            : null);
  }
}
