import 'dart:convert';

import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/models/general_models/m_response.dart';
import 'package:mc_common_app/models/subscriptions_models/branch_user_selection_model.dart';
import 'package:mc_common_app/models/subscriptions_models/provider_subscription_model.dart';
import 'package:mc_common_app/models/subscriptions_models/subscription_model.dart';
import 'package:mc_common_app/utils/enums.dart';
import 'package:mc_common_app/view_models/base_view_model.dart';
import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart';
import '../repositories/subscription_repo.dart';

class SubscriptionsVM extends BaseVM {
  final SubscriptionRepo subscriptionRepo;

  SubscriptionsVM({required this.subscriptionRepo});

  //All Subscriptions
  int selectedIndex = 0;
  late DropValue selectedMothlyTab;
  List<DropValue> monthlyTabs = [];
  late SubscriptionModel allSubscriptions;
  List<ProviderSubscriptionModel> mySubscriptionsBySp = [];
  List<Subscription> tempSubscriptions = [];

  //My Subscriptions

  //All Subscriptions
  getAllAvailableSubscriptions(String? serviceProviderID) async {
    selectedIndex = 0;
    setState(ViewState.busy);
    allSubscriptions = await subscriptionRepo.getAllSubscriptions(serviceProviderID);
    if (allSubscriptions.messageStatus == 1) {
      monthlyTabs.clear();
      var idSet = <int>{};
      for (var d in allSubscriptions.data ?? []) {
        if (idSet.add(d.durationDays ?? 0)) {
          monthlyTabs.add(DropValue(d.durationDays, _convertDaysToMonths(d.durationDays ?? 0), "", isEnabled: false));
        }
      }
      monthlyTabs.sort((a, b) => a.value.compareTo(b.value));
      monthlyTabs.first.isEnabled = true;
      selectedMothlyTab = monthlyTabs.first;
      filterSubscriptions();
      setState(ViewState.idle);
    } else {
      setState(ViewState.error);
    }
  }

  getSubscriptionBySP(String serviceProviderID, bool isRenew) async {
    selectedIndex = 0;
    setState(ViewState.busy);
    allSubscriptions = await subscriptionRepo.getSubscriptionBySP(serviceProviderID, isRenew);
    if (allSubscriptions.messageStatus == 1) {
      monthlyTabs.clear();
      var idSet = <int>{};
      for (var d in allSubscriptions.data ?? []) {
        if (idSet.add(d.durationDays ?? 0)) {
          monthlyTabs.add(DropValue(d.durationDays, _convertDaysToMonths(d.durationDays ?? 0), "", isEnabled: false));
        }
      }
      monthlyTabs.sort((a, b) => a.value.compareTo(b.value));
      monthlyTabs.first.isEnabled = true;
      selectedMothlyTab = monthlyTabs.first;

      filterSubscriptions();
      setState(ViewState.idle);
    } else {
      setState(ViewState.error);
    }
  }

  String newPrice = "";

  calculationUpgradePrice(String? serviceProviderID, String? newSubscription) async {
    setState(ViewState.busy);
    MResponse mResponse = await subscriptionRepo.calculationUpgradePrice(serviceProviderID, newSubscription);
    if (mResponse.messageStatus == 1) {
      setState(ViewState.idle);
      newPrice = mResponse.data.toString();
    } else {
      setState(ViewState.error);
    }
  }

  Future<MResponse> payForSubscription(int subscriptionId, bool isStartNow, bool isReview, String amount, {bool isDegrade = false, List<int>? listOfBranches, List<int>? listOfUsers}) async {
    Map<String, dynamic> map;
    if (isDegrade) {
      map = {
        // "id": subscription.id.toString(),
        // "payFortOrderID": 0,
        "providerID": AppState().getUser.data?.userInfo?.providerId.toString() ?? "",
        "subscriptionID": subscriptionId.toString(),
        "isStartNow": isStartNow.toString(),
        "subscriptionAmount": amount,
        "isRenew": isReview.toString(),
        "listOfBranches": listOfBranches,
        "listOfUsers": listOfUsers
      };
    } else {
      map = {
        // "id": subscription.id.toString(),
        // "payFortOrderID": 0,
        "providerID": AppState().getUser.data?.userInfo?.providerId.toString() ?? "",
        "subscriptionID": subscriptionId.toString(),
        "isStartNow": isStartNow.toString(),
        "subscriptionAmount": amount,
        "isRenew": isReview.toString()
        // "listOfBranches": [],
        // "listOfUsers": []
      };
    }
    MResponse mResponse = await subscriptionRepo.payForProviderSubscription(map);
    return mResponse;
  }

  Future<MResponse> createSubscriptionOrder(int subscriptionId, bool isStartNow, bool isRenew, {bool isDegrade = false, List<int>? listOfBranches, List<int>? listOfUsers}) async {
    Map<String, dynamic> map = {
      "providerID": AppState().getUser.data?.userInfo?.providerId.toString() ?? "",
      "subscriptionID": subscriptionId.toString(),
      "isStartNow": isStartNow.toString(),
      "isRenew": isRenew.toString()
    };
    MResponse mResponse = await subscriptionRepo.payForProviderSubscription(map);
    return mResponse;
  }

  List<BranchSelectionModel>? branchSelectionList;

  getSPBranchUser_Get() async {
    branchSelectionList = null;
    Map<String, String> map = {
      // "id": subscription.id.toString(),
      // "payFortOrderID": 0,
      "providerID": AppState().getUser.data?.userInfo?.providerId.toString() ?? "",
      // "listOfBranches": [],
      // "listOfUsers": []
    };
    branchSelectionList = await subscriptionRepo.getSPBranchUser_Get(map);
    if (branchSelectionList!.isNotEmpty) {
      branchSelectionList!.first.isOpend = true;
    }
    setState(ViewState.idle);
  }

  String _convertDaysToMonths(int days) {
    final int months = days ~/ 30;
    final int remainingDays = days % 30;

    String _result = months > 0 ? '$months Month${months > 1 ? 's' : ''}${remainingDays > 0 ? ' & ' : ''}' : '';
    _result += remainingDays > 0 ? '$remainingDays Day${remainingDays > 1 ? 's' : ''}' : '';
    return _result;
  }

  filterSubscriptions() {
    tempSubscriptions.clear();
    for (var element in allSubscriptions.data!) {
      if (selectedMothlyTab.id == element.durationDays) {
        tempSubscriptions.add(element);
      }
      if (element.id == AppState().getproviderSubscription.first.subscriptionID) {
        element.isMyCurrentPackage = true;
      }
    }
  }

  //My Subscriptions
  getMySubscriptions(String? serviceProviderID) async {
    selectedIndex = 0;
    setState(ViewState.busy);
    // allSubscriptions = await subscriptionRepo.getAllSubscriptions(serviceProviderID);
    allSubscriptions = await subscriptionRepo.getMySubscriptions(serviceProviderID);

    if (allSubscriptions.messageStatus == 1) {
      // allSubscriptions.data!.sort((a, b) => a.value.compareTo(b.value));
      setState(ViewState.idle);
    } else {
      setState(ViewState.error);
    }
  }

  // My Provider Subscription
  getMySubscriptionsBySP(String? serviceProviderID) async {
    setState(ViewState.busy);
    if (mySubscriptionsBySp.isEmpty) {
      mySubscriptionsBySp = await subscriptionRepo.getProviderSubscription(serviceProviderID: serviceProviderID);
      AppState().setproviderSubscription = mySubscriptionsBySp;
    }
    setState(ViewState.idle);
  }
}
