import 'dart:developer';

import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/models/general_models/generic_resp_model.dart';
import 'package:mc_common_app/models/subscriptions_models/branch_user_selection_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 selectedMonthlyTab;
  List<DropValue> monthlyTabs = [];
  late SubscriptionModel allSubscriptions;
  List<Subscription> 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;
  //     selectedMonthlyTab = 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;
      selectedMonthlyTab = monthlyTabs.first;

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

  String newPrice = "0.0";

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

  Future<GenericRespModel> 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": []
      };
    }
    GenericRespModel genericRespModel = await subscriptionRepo.payForProviderSubscription(map);
    return genericRespModel;
  }

  Future<GenericRespModel> 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()};
    GenericRespModel genericRespModel = await subscriptionRepo.payForProviderSubscription(map);
    return genericRespModel;
  }

  List<BranchSelectionModel>? branchSelectionList;

  getSPBranchUserGet() 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.getSPBranchUserGet(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 (selectedMonthlyTab.id == element.durationDays) {
        tempSubscriptions.add(element);
      }
      if (element.subscriptionTypeEnum == SubscriptionTypeEnum.current) {
        element.isMyCurrentPackage = true;
        // mySubscriptionsBySp.add(element);
      }
    }
  }

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

  // Rights
  // Branch CRUD
  // Services in Branch (CRUD)
  // Appointment Management
  // Request Management with Chat
  // Ads CRUD with Chat
  // General Chat

  // My Provider Subscription
  getMySubscriptionsBySP() async {
    mySubscriptionsBySp.clear();
    setState(ViewState.busy);
    // allSubscriptions.data
    for (var element in allSubscriptions.data!) {
      if (element.subscriptionTypeEnum == SubscriptionTypeEnum.current) {
        mySubscriptionsBySp.add(element);
      }
    }
    // mySubscriptionsBySp = await subscriptionRepo.getProviderSubscription(serviceProviderID: serviceProviderID);
    AppState().setproviderSubscription = mySubscriptionsBySp;

    setState(ViewState.idle);
  }
}
