import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:rasadyar_chicken/data/data_source/local/chicken_local.dart';
import 'package:rasadyar_chicken/data/di/chicken_di.dart';
import 'package:rasadyar_chicken/data/models/local/widely_used_local_model.dart';
import 'package:rasadyar_chicken/data/models/response/inventory/inventory_model.dart';
import 'package:rasadyar_chicken/data/models/response/iran_province_city/iran_province_city_model.dart';
import 'package:rasadyar_chicken/data/models/response/roles_products/roles_products.dart';
import 'package:rasadyar_chicken/data/models/response/steward_sales_info_dashboard/steward_sales_info_dashboard.dart';
import 'package:rasadyar_chicken/data/repositories/chicken/chicken_repository.dart';
import 'package:rasadyar_chicken/presentation/pages/common/profile/view.dart';
import 'package:rasadyar_chicken/presentation/pages/steward/buy/view.dart';
import 'package:rasadyar_chicken/presentation/pages/steward/home/view.dart';
import 'package:rasadyar_chicken/presentation/pages/steward/sale/view.dart';
import 'package:rasadyar_chicken/presentation/pages/steward/segmentation/view.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 StewardRootLogic extends GetxController {
  DateTime? _lastBackPressed;
  RxInt currentPage = 2.obs;
  List<Widget> pages = [BuyPage(), SalePage(), HomePage(), SegmentationPage(), ProfilePage()];

  final defaultRoutes = <int, String>{0: ChickenRoutes.buySteward, 1: ChickenRoutes.saleSteward};
  RxList<ProductModel> rolesProductsModel = RxList<ProductModel>();
  Rxn<WidelyUsedLocalModel> widelyUsedList = Rxn<WidelyUsedLocalModel>();
  Rxn<StewardSalesInfoDashboard> stewardSalesInfoDashboard = Rxn<StewardSalesInfoDashboard>();

  late DioRemote dioRemote;
  var tokenService = Get.find<TokenStorageService>();
  late ChickenRepository chickenRepository;
  late ChickenLocalDataSource localDatasource;

  RxList<ErrorLocationType> errorLocationType = RxList();
  RxMap<int, dynamic> inventoryExpandedList = RxMap();
  Rxn<InventoryModel> inventoryModel = Rxn<InventoryModel>();
  RxList<IranProvinceCityModel> provinces = <IranProvinceCityModel>[].obs;

  // Cancel tokens for API calls
  CancelToken? _inventoryCancelToken;
  CancelToken? _provincesCancelToken;

  @override
  void onInit() {
    super.onInit();
    localDatasource = diChicken.get<ChickenLocalDataSource>();
    chickenRepository = diChicken.get<ChickenRepository>();

    /*localDatasource.openBox().then((value) async {
      widelyUsedList.value = localDatasource.getAllWidely();
    });*/
  }

  @override
  void onReady() {
    super.onReady();

    if (provinces.isEmpty) {
      getProvinces();
    }
    if (inventoryModel.value == null) {
      getInventory();
    }
    if (rolesProductsModel.isEmpty) {
      getRolesProducts();
    }
    getStewardSaleDashboard();

    if (widelyUsedList.value?.hasInit != true) {
      //TODO
      localDatasource.initWidleyUsed().then((value) => localDatasource.getAllWidely());
    }
  }

  @override
  void onClose() {
    // Cancel any ongoing requests when controller is disposed
    _inventoryCancelToken?.cancel();
    _provincesCancelToken?.cancel();
    super.onClose();
  }

  Future<void> onRefresh() async {
    await Future.wait([
      getInventory(),
      getRolesProducts(),
      getStewardSaleDashboard(),
      getProvinces(),
    ]);
  }

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

  Future<void> getInventory() async {
    // Cancel previous request if still running
    _inventoryCancelToken?.cancel();
    _inventoryCancelToken = CancelToken();

    await safeCall<List<InventoryModel>?>(
      call: () async => await chickenRepository.getInventory(
        token: tokenService.accessToken.value!,
        cancelToken: _inventoryCancelToken,
      ),
      onSuccess: (result) {
        if (result != null) {
          inventoryModel.value = result.first;
        }
      },
      onError: (error, stackTrace) {
        if (error is DioException && error.type == DioExceptionType.cancel) {
          // Request was cancelled, ignore the error
          return;
        }
      },
    );
  }

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

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

  Future<void> getProvinces() async {
    // Cancel previous request if still running
    _provincesCancelToken?.cancel();
    _provincesCancelToken = CancelToken();

    try {
      final res = await chickenRepository.getProvince(cancelToken: _provincesCancelToken);
      if (res != null) {
        provinces.clear();
        provinces.value = res;
      }
    } catch (e) {
      if (e is DioException && e.type == DioExceptionType.cancel) {
        // Request was cancelled, ignore the error
        return;
      }
      provinces.clear();
    }
  }

  Future<void> getRolesProducts() async {
    safeCall(
      call: () async =>
          await chickenRepository.getRolesProducts(token: tokenService.accessToken.value!),
      onSuccess: (result) {
        if (result != null) {
          rolesProductsModel.value = result;
        }
      },
      onError: (error, stacktrace) {},
    );
  }

  Future<void> getStewardSaleDashboard() async {
    safeCall(
      call: () async => await chickenRepository.getStewardSalesInfoDashboard(
        token: tokenService.accessToken.value!,
        queryParameters: buildRawQueryParams(role: 'Steward'),
      ),
      onSuccess: (result) {
        if (result != null) {
          stewardSalesInfoDashboard.value = result;
        }
      },
      onError: (error, stacktrace) {},
    );
  }

  int getNestedKey() {
    switch (currentPage.value) {
      case 0:
        return stewardFirstKey;
      case 1:
        return stewardSecondKey;
      case 2:
        return stewardThirdKey;

      case 3:
        return stewardFourthKey;

      case 4:
        return stewardFourthKey;

      default:
        return stewardThirdKey;
    }
  }

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

    final currentRoute = currentNestedKey?.currentState;


    fLog("onPopScopTaped ==> ${currentNestedKey?.currentState?.canPop()}");
    if (currentNestedKey?.currentState?.canPop() == true) {
      iLog(currentNestedKey?.currentState?.canPop());
      iLog(currentNestedKey?.currentContext );
      currentNestedKey?.currentState?.popUntil((route) => route.isFirst);

    } 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();
      }
    }
  }
}
