import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:rasadyar_auth/data/services/token_storage_service.dart';
import 'package:rasadyar_auth/data/utils/safe_call.dart';
import 'package:rasadyar_chicken/data/datasource/local/chicken_local_imp.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/repositories/chicken_repository.dart';
import 'package:rasadyar_chicken/data/repositories/chicken_repository_imp.dart';
import 'package:rasadyar_chicken/presentation/pages/buy/view.dart';
import 'package:rasadyar_chicken/presentation/pages/home/view.dart';
import 'package:rasadyar_chicken/presentation/pages/profile/view.dart';
import 'package:rasadyar_chicken/presentation/pages/sale/view.dart';
import 'package:rasadyar_chicken/presentation/pages/segmentation/view.dart';
import 'package:rasadyar_chicken/presentation/routes/routes.dart';
import 'package:rasadyar_chicken/presentation/utils/utils.dart';
import 'package:rasadyar_core/core.dart';

enum ErrorLocationType { serviceDisabled, permissionDenied, none }

class RootLogic extends GetxController {
  RxInt currentPage = 2.obs;
  List<Widget> pages = [BuyPage(), SalePage(), HomePage(), SegmentationPage(), ProfilePage()];

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

  late DioRemote dioRemote;
  var tokenService = Get.find<TokenStorageService>();
  late ChickenRepository chickenRepository;
  late ChickenLocalDataSourceImp 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<ChickenLocalDataSourceImp>();
    chickenRepository = diChicken.get<ChickenRepositoryImp>();
    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();
    }

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

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

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

  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) {},
    );
  }

}
