import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/Addresses.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/LacumAccountInformation.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/ShippingOption.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCart.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCartResponse.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/order_detail.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/payment-checkout-data.dart';
import 'package:diplomaticquarterapp/core/service/parmacyModule/order-preview-service.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart';

import '../../../locator.dart';
import '../base_view_model.dart';

class OrderPreviewViewModel extends BaseViewModel {
  OrderPreviewService _orderService = locator<OrderPreviewService>();

  List<Addresses> get addresses => _orderService.addresses;

  LacumAccountInformation get lacumInformation => _orderService.lacumInformation;

  List<OrderDetailModel> get orderListModel => _orderService.orderList;

  PharmacyModuleViewModel pharmacyModuleViewModel = locator<PharmacyModuleViewModel>();

  ShoppingCartResponse cartResponse = ShoppingCartResponse();
  PaymentCheckoutData paymentCheckoutData = PaymentCheckoutData();
  double totalAdditionalShippingCharge = 0;

  setShoppingCartResponse(ShoppingCartResponse cart) {
    cartResponse = cart;
    notifyListeners();
  }

  Future getOrderPreviewData() async {
    setState(ViewState.Busy);
    await _orderService.getAddresses();
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.Error);
    } else {
      getShoppingCart();
    }
  }

  void update() {
    notifyListeners();
  }

  Future getShoppingCart() async {
    // setState(ViewState.Busy);
    // GifLoaderDialogUtils.showMyDialog(
    //     locator<NavigationService>().navigatorKey.currentContext);
    await _orderService.getShoppingCart().then((res) {
      if (res != null) _handleGetShoppingCartResponse(res);
    });
    if (_orderService.hasError) {
      error = _orderService.error;
      // setState(ViewState.Error);
    } else {
      if (paymentCheckoutData != null) {
        paymentCheckoutData.cartDataVisible = true;
      }
      // GifLoaderDialogUtils.hideDialog(
      //     locator<NavigationService>().navigatorKey.currentContext);
      setState(ViewState.Idle);
    }
  }

  Future<ShoppingCartResponse> changeProductQuantity(ShoppingCart product) async {
    setState(ViewState.BusyLocal);
    var resp = await _orderService.changeProductQuantity(product.id, product);

    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.ErrorLocal);
    } else {
      var object = _handleGetShoppingCartResponse(resp);
      setState(ViewState.Idle);
    }
    // return object;
  }

  Future<ShoppingCartResponse> deleteProduct(ShoppingCart product) async {
    setState(ViewState.BusyLocal);
    var resp = await _orderService.deleteProduct(product.id);
    var object = _handleGetShoppingCartResponse(resp);
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.ErrorLocal);
    } else {
      setState(ViewState.Idle);
    }
    return object;
  }

  Future deleteShoppingCart() async {
    setState(ViewState.Busy);
    await _orderService.deleteShoppingCart().then((res) {
      _handleGetShoppingCartResponse(res);
    });
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.Error);
    } else {
      setState(ViewState.Idle);
    }
  }

  ShoppingCartResponse _handleGetShoppingCartResponse(Map res) {
    cartResponse.totalAmount = 0.0;
    totalAdditionalShippingCharge = 0;
    if (res == null) {
      error = "response is null";
      setState(ViewState.Error);
      return null;
    }
    cartResponse.itemCount = res["item_count"];
    cartResponse.quantityCount = res["quantity_count"];
    cartResponse.subtotal = res["subtotal"];
    cartResponse.subtotalWithVat = res["subtotal_with_vat"];
    cartResponse.subtotalVatAmount = res["subtotal_vat_amount"];
    cartResponse.subtotalVatRate = res["subtotal_vat_rate"];
    cartResponse.shoppingCarts = List();

    if (paymentCheckoutData.shippingOption != null) {
      totalAdditionalShippingCharge = paymentCheckoutData.shippingOption.rate;
      cartResponse.subtotalVatAmount += paymentCheckoutData.shippingOption.rateVat;
      cartResponse.totalAmount += (paymentCheckoutData.shippingOption.rate + paymentCheckoutData.shippingOption.rateVat);
    }

    res["shopping_carts"].forEach((item) {
      ShoppingCart shoppingCart = ShoppingCart.fromJson(item);
      cartResponse.shoppingCarts.add(shoppingCart);
      totalAdditionalShippingCharge += shoppingCart.product.additionalShippingCharge;
    });
    if (paymentCheckoutData.shippingOption != null) cartResponse.totalAmount = (cartResponse.subtotalWithVat + totalAdditionalShippingCharge + paymentCheckoutData.shippingOption.rateVat);
    return cartResponse;
  }

  String getPaymentOptionImage(PaymentOption paymentOption) {
    String assetFile = "assets/images/pharmacy_module/payment/";
    switch (paymentOption.index) {
      case 0:
        return "${assetFile}mada.png";
        break;
      case 1:
        return "${assetFile}sadad.png";
        break;
      case 2:
        return "${assetFile}visa.png";
        break;
      case 3:
        return "${assetFile}mastercard.png";
        break;
      case 4:
        return "${assetFile}installment.png";
        break;
      case 5:
        return "${assetFile}applePay.png";
      default:
        return "";
    }
  }

  String getPaymentOptionName(PaymentOption paymentOption) {
    return _orderService.getPaymentOptionName(paymentOption);
  }

  getInformationsByAddress(String identificationNo) async {
    await getShippingOption(identificationNo);
  }

  getLacumAccountInformation(String identificationNo) async {
    setState(ViewState.Busy);
    await _orderService.getLacumAccountInformation(identificationNo);
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.Error);
    } else {
      if (_orderService.lacumInformation.yahalaAccountNo != 0) getLacumGroupData(identificationNo);
    }
  }

  Future getLacumGroupData(String identificationNo) async {
    setState(ViewState.Busy);
    await _orderService.getLacumGroupInformation(identificationNo);
    paymentCheckoutData.lacumInformation = _orderService.lacumGroupInformation;
    paymentCheckoutData.usedLakumPoints = paymentCheckoutData.lacumInformation.lakumInquiryInformationObjVersion.pointsBalanceAmount;
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.Error);
    } else {
      setState(ViewState.Idle);
    }
  }

  Future getShippingOption(String identificationNo) async {
    setState(ViewState.Busy);
    await _orderService.getShippingOption(paymentCheckoutData.address).then((res) async {
      if (_orderService.hasError) {
        error = _orderService.error;
        setState(ViewState.Error);
      } else {
        paymentCheckoutData.shippingOption = ShippingOption.fromJson(res);
        setState(ViewState.Idle);
        await getLacumAccountInformation(identificationNo);
      }
    });
  }

  Future makeOrder(bool isLakumEnabled) async {
    setState(ViewState.Busy);
    await pharmacyModuleViewModel.generatePharmacyToken();

    await _orderService.makeOrder(paymentCheckoutData, cartResponse.shoppingCarts, isLakumEnabled);
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.ErrorLocal);
    } else {
      setState(ViewState.Idle);
    }
  }

  bool isCartItemsOutOfStock() {
    bool outOfStock = false;
    for (int i = 0; i < cartResponse.shoppingCarts.length; i++) {
      if (cartResponse.shoppingCarts[i].product.stockQuantity == 0) {
        outOfStock = true;
        break;
      }
    }
    return outOfStock;
  }
}

enum PaymentOption { meda, sadad, visa, mastercard, installments, applepay }
