import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rasadyar_chicken/data/di/chicken_di.dart';
import 'package:rasadyar_chicken/data/repositories/poultry_science/poultry_science_repository.dart';
import 'package:rasadyar_chicken/presentation/pages/common/profile/view.dart';
import 'package:rasadyar_chicken/presentation/pages/poultry_science/home/view.dart';
import 'package:rasadyar_chicken/presentation/pages/poultry_science/poultry_action/view.dart';
import 'package:rasadyar_chicken/presentation/routes/pages.dart';
import 'package:rasadyar_chicken/presentation/routes/routes.dart';
import 'package:rasadyar_chicken/presentation/utils/nested_keys_utils.dart';
import 'package:rasadyar_chicken/presentation/utils/utils.dart';
import 'package:rasadyar_core/core.dart';

enum ErrorLocationType { serviceDisabled, permissionDenied, none }

class PoultryScienceRootLogic extends GetxController {
  var tokenService = Get.find<TokenStorageService>();

  late PoultryScienceRepository poultryRepository;

  RxList<ErrorLocationType> errorLocationType = RxList();
  RxMap<int, dynamic> homeExpandedList = RxMap();
  DateTime? _lastBackPressed;

  RxInt currentPage = 1.obs;

  final pages = [
     Navigator(
      key: Get.nestedKey(poultryFirstKey),
      onGenerateRoute: (settings) {
        final page = ChickenPages.pages.firstWhere(
          (e) => e.name == settings.name,
          orElse: () => ChickenPages.pages.firstWhere(
            (e) => e.name == ChickenRoutes.actionPoultryScience,
          ),
        );

        return buildRouteFromGetPage(page);
      },
    ),
    PoultryScienceHomePage(),
    ProfilePage(),


  ];

  @override
  void onInit() {
    super.onInit();
    poultryRepository = diChicken.get<PoultryScienceRepository>();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void toggleExpanded(int index) {
    if (homeExpandedList.keys.contains(index)) {
      homeExpandedList.remove(index);
    } else {
      homeExpandedList[index] = false;
    }
  }

  void rootErrorHandler(DioException error) {
    handleGeneric(error, () {
      tokenService.deleteModuleTokens(Module.chicken);
    });
  }

  void changePage(int index) {
    currentPage.value = index;
  }

  int getNestedKey() {
    switch (currentPage.value) {
      case 0:
        return poultryFirstKey;
      case 1:
        return poultrySecondKey;
      case 2:
        return poultryThirdKey;
      default:
        return poultryFirstKey;
    }
  }

  void popBackTaped()  async{
    final nestedKeyId = getNestedKey();
    GlobalKey<NavigatorState>? currentNestedKey = Get.nestedKey(nestedKeyId);

    if (currentNestedKey?.currentState?.canPop() == true) {
      Get.back(id: nestedKeyId);
    } else {
      final now = DateTime.now();
      if (_lastBackPressed == null ||
          now.difference(_lastBackPressed!) > Duration(seconds: 2)) {
        _lastBackPressed = now;
        Get.snackbar(
          'خروج از برنامه',
          'برای خروج دوباره بازگشت را بزنید',
          snackPosition: SnackPosition.TOP,
          duration: Duration(seconds: 2),
          backgroundColor: AppColor.warning,
        );
      } else {
        await SystemNavigator.pop();
      }
    }
  }
}
