import 'dart:convert';
import 'package:another_flushbar/flushbar.dart';
import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
import 'package:page_transition/page_transition.dart';
import 'package:telnow_mobile_new/src/injector/injector.dart';
import 'package:telnow_mobile_new/src/layouts/auth/qr.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/history_forum.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/message_list.dart';
import 'U.dart';
import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
import 'package:telnow_mobile_new/src/api/jwt_token.dart';

enum ErrorType {
  noInternet, serverError, connectionError, invalidAccount, expiredAccount
}
final SharedPreferencesManager _sharedPreferencesManager = locator<SharedPreferencesManager>();
final JwtToken token = JwtToken();

class UIService {
  static final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  static BuildContext? get context => navigatorKey.currentContext;

  static void goNotification(Map<String, dynamic> list) {
    final ctx = context;
    if (ctx == null) return;

    if (list['type'] == 'MESSAGE') {
      Navigator.push(
        ctx,
        PageTransition(
          type: PageTransitionType.rightToLeft,
          child: MobMessageListPage(null),
        ),
      );
    } else if (list['type'] == 'FORUM') {
      Navigator.push(
        ctx,
        PageTransition(
          type: PageTransitionType.rightToLeft,
          child: MobHistoryForumPage(
            data: jsonDecode(list['requestHistory']),
          ),
        ),
      );
    } else {
      final pid = U.getPidFromUrl(ctx.router.currentUrl);
      ctx.router.removeLast();
      ctx.navigateToPath("/app/$pid/menu/history");
    }
  }

  static void navigateTo(Widget child) {
    final ctx = context;
    if (ctx != null) {
      Navigator.push(ctx, PageTransition(type: PageTransitionType.rightToLeft, child: child));
    }
  }

  static void navigateNamed(String routePath) {
    final ctx = context;
    if (ctx != null) {
      AutoRouter.of(ctx).removeLast();
      AutoRouter.of(ctx).navigatePath(routePath);
    }
  }

  static void navigateBack({exc = false}){
    final ctx = context;
    if (ctx != null) {
      Navigator.of(ctx).pop(exc);
    }
  }

  static void showError(String message) {
    final ctx = context;
    if (ctx != null) {
      Flushbar(
        message: message,
        icon: Icon(
          Icons.info_outline,
          size: 28.0,
          color: Colors.red,
        ),
        duration: Duration(seconds: 5),
        flushbarPosition: FlushbarPosition.BOTTOM,
        margin: EdgeInsets.all(8),
        borderRadius: BorderRadius.all(Radius.circular(8)),
      ).show(ctx);
    }
  }

  static void showSuccess(message) {
    final ctx = context;
    if (ctx != null) {
      Flushbar(
        message: message,
        icon: Icon(
          Icons.info_outline,
          size: 28.0,
          color: Colors.green,
        ),
        duration: Duration(seconds: 5),
        flushbarPosition: FlushbarPosition.BOTTOM,
        margin: EdgeInsets.all(8),
        borderRadius: BorderRadius.all(Radius.circular(8)),
      ).show(ctx);
    }
  }

  static bool get isCurrentRouteInactive {
    final ctx = context;
    final route = ModalRoute.of(ctx ?? navigatorKey.currentState?.context ?? ctx!);
    return route?.isCurrent != true;
  }

  static void pop() {
    navigatorKey.currentState?.maybePop();
  }

  static void setLocale(code) {
    final ctx = context;
    if(ctx == null) return;
    ctx.setLocale(code);
  }

  static String getLocale() {
    return context!.locale.toString();
  }

  static void showLoading({String? text, String? lottie}){
    final ctx = context;
    if(ctx == null) return;
    showDialog(
      context: ctx,
      barrierDismissible: false,
      barrierColor: lottie != null ? Colors.white : null,
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: () => Future.value(false),
            child: Material(
              type: MaterialType.transparency,
              child: Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    lottie != null
                        ? Lottie.asset('assets/image/lottie/$lottie', width: 250, height: 250, fit: BoxFit.fill)
                        : CircularProgressIndicator(color: primaryColor),
                    SizedBox(height: 5),
                    Text(
                      text ?? 'inProcess'.tr(),
                      style: TextStyle(color: lottie != null ? Colors.black : Colors.white),
                    ),
                  ],
                ),
              ),
            ),
          );
        }
    );
  }

  static void closeLoading(){
    Navigator.of(navigatorKey.currentContext!, rootNavigator: true).pop();
  }

  static void handlingError(ErrorType type) {
    var data = [
      {
        'image': 'NoInternet.png',
        'title': 'noInternetTitle'.tr(),
        'description': 'noInternetDesc'.tr()
      },
      {
        'image': 'ErrorServer.png',
        'title': 'errorServerTitle'.tr(),
        'description': 'errorServerDesc'.tr()
      },
      {
        'image': 'ErrorConnection.png',
        'title': 'errorConnectTitle'.tr(),
        'description': 'errorConnectDesc'.tr()
      },
      {
        'image': 'ErrorAuth.png',
        'title': 'invalidAccountTitle'.tr(),
        'description': 'invalidAccountDesc'.tr()
      },
      {
        'image': 'ErrorAuth.png',
        'title': 'expAccountTitle'.tr(),
        'description': 'expAccountDesc'.tr()
      }
    ];
    int idx = type.index;

    final ctx = context;
    if (ctx == null) return;

    void clearSharedPreferencesKey(){
      _sharedPreferencesManager.clearKey(SharedPreferencesManager.keyAccessCode);
      _sharedPreferencesManager.clearKey(SharedPreferencesManager.keySerialCode);
      _sharedPreferencesManager.clearKey(SharedPreferencesManager.keyAccessToken);
      _sharedPreferencesManager.clearKey(SharedPreferencesManager.keyRefreshToken);
      _sharedPreferencesManager.clearKey(SharedPreferencesManager.keyUsername);
      _sharedPreferencesManager.clearKey(SharedPreferencesManager.keyIsLogin);
      _sharedPreferencesManager.clearKey(SharedPreferencesManager.keyScoope);
      _sharedPreferencesManager.clearKey(SharedPreferencesManager.debugString);
      _sharedPreferencesManager.clearKey(SharedPreferencesManager.keyHistoryMark);
    }

    showModalBottomSheet<void>(
      context: ctx,
      backgroundColor: Colors.white,
      isDismissible: false,
      enableDrag: false,
      builder: (BuildContext context) {
        return SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Container(
                padding: const EdgeInsets.fromLTRB(15, 10, 15, 0),
                alignment: Alignment.centerRight,
                child: GestureDetector(
                  child: Icon(Icons.clear),
                  onTap: () => Navigator.of(context).pop(),
                ),
              ),
              Container(
                width: 200,
                padding: const EdgeInsets.fromLTRB(15, 0, 15, 10),
                child: Image(
                  image: AssetImage('assets/image/error/${data[idx]['image']!}'))),
              Padding(
                padding: const EdgeInsets.fromLTRB(15, 0, 15, 10),
                child: Text(data[idx]['title']!,
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
                  textAlign: TextAlign.center),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(15, 0, 15, 10),
                child: Text(data[idx]['description']!,
                  style: TextStyle(fontSize: 14),
                  textAlign: TextAlign.center),
              ),
              if (idx > 2)
              Padding(
                padding: const EdgeInsets.fromLTRB(15, 0, 15, 10),
                child: SizedBox(
                  width: double.infinity,
                  height: 45,
                  child: TextButton(
                    style: ButtonStyle(
                      backgroundColor:
                      WidgetStateProperty.all<Color>(primaryColor),
                      shape: WidgetStateProperty.all<
                        RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(5),
                        ))),
                    child: Text('logout'.tr().toUpperCase(),
                      style: TextStyle(color: Colors.white),
                      textAlign: TextAlign.center),
                    onPressed: () {
                      if (idx == 4) {
                        clearSharedPreferencesKey();
                        Navigator.pushAndRemoveUntil(
                          context,
                          MaterialPageRoute(
                            builder: (context) => NewQrPage()),
                          ModalRoute.withName("/home"));
                      } else {
                        var pid = U.getPidFromUrl(context.router.currentUrl);
                        token.logout();
                        context.router.removeLast();
                        context.navigateToPath("/app/$pid/login");
                      }
                    },
                  )),
              )
            ],
          ),
        );
      });
  }

  static String getCurrentUrl(){
    final ctx = context;
    if(ctx == null) return '';
    return ctx.router.currentUrl;
  }
}
