import 'dart:convert';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/api/jwt_token.dart';
import 'package:telnow_mobile_new/src/injector/injector.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/request_create.dart';
import 'package:telnow_mobile_new/src/layouts/web/request_create.dart';
import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/cache_manager.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';
import 'package:telnow_mobile_new/src/utils/ui_service.dart';

enum HistoryTab {
  ongoing,
  done;

  List get filters {
    switch(this){
      case HistoryTab.ongoing:
        return [
          {'title': 'stateQueue'.tr(), 'value': 'queue', 'filter': '{"or":[{"f":["currentState","EQ","DIANTRIKAN"]},{"f":["currentState","EQ","DIPROSES"]}]}'},
          {'title': 'stateDone'.tr(), 'value': 'done', 'filter': '{"f":["currentState","EQ","DIMULAI"]}'},
          {'title': 'hold'.tr(), 'value': 'hold', 'filter': '{"f":["currentState","EQ","HOLD"]}'}
        ];
      case HistoryTab.done:
        return [
          {'title': 'stateFinish'.tr(), 'value': 'finish', 'filter': '{"or":[{"f":["currentState","EQ","DISELESAIKAN"]},{"f":["currentState","EQ","TUNTAS"]}]}'},
          {'title': 'stateCancel'.tr(), 'value': 'cancel', 'filter': '{"f":["currentState","EQ","DIBATALKAN"]}'}
        ];
    }
  }
}
class HistoryFunction{
  final JwtToken token = JwtToken();
  final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();

  final BuildContext context = UIService.context!;
  late final HistoryModule historyModule = Provider.of<HistoryModule>(context, listen: false);
  late final UserModule userModule = Provider.of<UserModule>(context, listen: false);

  List filterList = [
    {'title': 'stateQueue'.tr(), 'value': 1, 'filter': '{"or":[{"f":["currentState","EQ","DIANTRIKAN"]},{"f":["currentState","EQ","DIPROSES"]}]}'},
    {'title': 'stateDone'.tr(), 'value': 2, 'filter': '{"f":["currentState","EQ","DIMULAI"]}'},
    {'title': 'hold'.tr(), 'value': 3, 'filter': '{"f":["currentState","EQ","HOLD"]}'},
    {'title': 'stateFinish'.tr(), 'value': 4, 'filter': '{"or":[{"f":["currentState","EQ","DISELESAIKAN"]},{"f":["currentState","EQ","TUNTAS"]}]}'},
    {'title': 'stateCancel'.tr(), 'value': 5, 'filter': '{"f":["currentState","EQ","DIBATALKAN"]}'}
  ];

  List doneList = [
    {'title': 'stateFinish'.tr(), 'value': 4, 'filter': '{"or":[{"f":["currentState","EQ","DISELESAIKAN"]},{"f":["currentState","EQ","TUNTAS"]}]}'},
    {'title': 'stateCancel'.tr(), 'value': 5, 'filter': '{"f":["currentState","EQ","DIBATALKAN"]}'},
  ];

  List ongoingList = [
    {'title': 'stateQueue'.tr(), 'value': 1, 'filter': '{"or":[{"f":["currentState","EQ","DIANTRIKAN"]},{"f":["currentState","EQ","DIPROSES"]}]}'},
    {'title': 'stateDone'.tr(), 'value': 2, 'filter': '{"f":["currentState","EQ","DIMULAI"]}'},
    {'title': 'hold'.tr(), 'value': 3, 'filter': '{"f":["currentState","EQ","HOLD"]}'},
  ];

  getActiveForum({bool loadAfterAction = false}) async {
    try {
      String urlForum = '/api/notifications/search/forumNotification';

      var val = await CacheMan.readData(urlForum);
      if (val != null) {
        historyModule.setActiveForum(val['data']);
      }

      var data = await apiAuthProvider.getData(urlForum, null);
      if (data != null) {
        historyModule.setActiveForum(data);
        CacheMan.writeData(urlForum, data);
      }
      // kayaknya ga guna getUser disini. 031125
      // getUser();
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  getUser() async {
    try {
      var res = await token.getUserData();
      if (res != null) {
        userModule.setList(res);
        // dipindah di event onRefresh, paralel sama get notifForum. 031125
        // getMission();
      } else {
        userModule.setResetData(true);
      }
    } catch (e) {
      userModule.setResetData(true);
    }
  }

  getMission() async {
    HistoryTab tab = historyModule.activeTab();
    List filters = tab.filters;
    String selectedFilter = historyModule.selectedFilter();
    String state = '${tab.name}::$selectedFilter';

    try {
      // debugPrint('historyModule.isLoadHistory(state: state): ${historyModule.isLoadHistory(state: state)}');
      if (!historyModule.isLoadHistory(state: state) && !historyModule.stopLoadHistory()) {
        historyModule.setLoadHistory(true, state);
        var sort = ['datetimeRequest,desc'];
        String filter;

        // If no selected filter button, use default filter;
        if(selectedFilter == 'none'){
          if(historyModule.activeTab().name == "done"){
            filter = '{"or":[{"f":["currentState","EQ","DISELESAIKAN"]},{"f":["currentState","EQ","TUNTAS"]},{"f":["currentState","EQ","DIBATALKAN"]}]}';
          } else {
            filter = '{"or":[{"f":["currentState","EQ","DIANTRIKAN"]},{"f":["currentState","EQ","DIPROSES"]},{"f":["currentState","EQ","DIMULAI"]}]}';
          }
        } else {
          filter = filters.firstWhere((f) => f['value'] == selectedFilter)['filter'];
        }

        // If no internet connection and selected status is On going and filter button is Queued, display pending data.
        if(historyModule.activeTab().name == "ongoing" && (selectedFilter == 'none' || selectedFilter == 'queue') && !U.getInternetStatus()){
          List pendingList = sharedPreferencesManager.isKeyExists(SharedPreferencesManager.keyPendingData)!?jsonDecode(sharedPreferencesManager.getString(SharedPreferencesManager.keyPendingData)!):[];
          historyModule.setPendingData(pendingList);
        }

        String url = '/api/requestHistories/search/myReqHistory';

        String key = url + filter;
        var val = await CacheMan.readData(key);
        if (val != null && historyModule.page() == 0) {
          historyModule.setDataRequests(state, val['data']);
        }

        var mission = await apiAuthProvider.getData(url, {'size': '30', 'page': historyModule.page().toString(), 'sort': sort, 'filter': filter});
        if (mission != null){
          // debugPrint("Cek tekan kene!!");
          historyModule.setLoadHistory(false, state);
          List tempData = [];
          if (mission.containsKey('_embedded')) {
            // debugPrint('Balikan data: ${mission['_embedded']['requestHistories'].length}');
            for (int i = 0; i < mission['_embedded']['requestHistories'].length; i++) {
              var isFrm = false;
              String id = "";
              String msg = "";

              historyModule.activeForum().forEach((el) {
                if (el['ticketId'] == mission['_embedded']['requestHistories'][i]['ticketNo']) {
                  id = el['id'];
                  msg = el['desc'];
                }
              });

              if (id != "") isFrm = true;
              mission['_embedded']['requestHistories'][i]['_hasForum'] = isFrm;
              mission['_embedded']['requestHistories'][i]['_forumId'] = id;
              mission['_embedded']['requestHistories'][i]['_forumMsg'] = msg;

              tempData.add(mission['_embedded']['requestHistories'][i]);
            }
          }

          // debugPrint('Filter Index: ${indexFilterSelected} & Filter: $filter');
          // historyModule.setLoadHistory(false);
          if (tempData.isEmpty) {
            historyModule.setStopLoadHistory(true);
            historyModule.clearDataRequests();
            CacheMan.writeData(key, tempData);
          } else {
            if (historyModule.page() == 0) {
              CacheMan.writeData(key, tempData);
              historyModule.clearDataRequests();
            }
            historyModule.addPage();
          }
          historyModule.setDataRequests(state, tempData);

          if (historyModule.getMisiLength() >= mission['page']['totalElements']) {
            historyModule.setStopLoadHistory(true);
          }
        } else {
          historyModule.setLoadHistory(false, state);
          historyModule.setStopLoadHistory(true);
        }
      }
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  onRefresh() async {
    historyModule.setCurrentPage();
    historyModule.clearDataRequests();
    historyModule.setPendingData([]);
    historyModule.setActiveForum([]);
    historyModule.setSelectedIndexes([]);
    historyModule.setMultiSelectMode(false);
    historyModule.setStopLoadHistory(false);
    historyModule.setPage(0);
    getMission();
    getActiveForum();
  }

  bool askForRate(list) {
    if (list['satisfactionRate'] == 0 && list['servantGroup'] != "#autoresponse") {
      return true;
    }
    return false;
  }

  bool isAutoResponse(list) {
    if (list['servantGroup'] == "#autoresponse") {
      return true;
    }
    return false;
  }

  selectedController(BuildContext context, i) {
    if (historyModule.selectedIndexes().contains(i)) {
      historyModule.removeSelectedIndexes(i);
    } else {
      historyModule.addSelectedIndexes(i);
    }
    historyModule.setMultiSelectMode(historyModule.selectedIndexes().isEmpty ? false : true);
  }

  deleteData(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext contextt) {
        return AlertDialog(
          title: Text("deleteHistory".tr(), style: TextStyle(fontSize: 18),
          ),
          content: Text("deleteHistoryConfirm".tr()),
          actions: <Widget>[
            TextButton(
              child: Text("buttonNo".tr()),
              onPressed: () {
                Navigator.of(contextt).pop();
              },
            ),
            TextButton(
                onPressed: () async {
                  Navigator.of(contextt).pop();
                  List<String> params = [];
                  historyModule.selectedIndexes().forEach((e) {
                    params.add(historyModule.dataRequests()[e]["ticketNo"]);
                  });
                  var res = await apiAuthProvider.postData("/api/requestHistories/deleteMyHistory", {"ticketNumbers": params}, null);
                  if (res != null) {
                    onRefresh();
                  }
                },
                child: Text("buttonYes".tr())),
          ],
        );
      },
    );
  }

  requestAgainAction(int i) async{
    final isWebView = U.webView(context);
    try {
      String tenant = '';
      String filter = '';

      if ((historyModule.dataRequests()[i]['requestGroupCode']).split(" ").length != 1) {
        tenant = ',{"f":["tenantCode","EQ","${(historyModule.dataRequests()[i]['requestGroupCode']).split(" ").first}"]}';
      }
      filter = '{"and":[{"f":["code","EQ","${historyModule.dataRequests()[i]['requestCode']}"]}$tenant]}';

      var res = await apiAuthProvider.getData('/api/requests/search/customFind', {'filter': filter});
      if (res != null) {
        if (res.containsKey('_embedded')) {
          UIService.navigateTo(
            isWebView ?
              WebReqCreatePage(user: userModule.user(), request: res['_embedded']['requests'][0]) :
              MobReqCreatePage(user: userModule.user(), request: res['_embedded']['requests'][0])
          );
        } else {
          UIService.showError('reqCodeNotFound'.tr());
        }
      }
    } catch (e) {
      UIService.showError(e.toString());
      debugPrint(e.toString());
    }
  }
}