import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_request.dart';
import '../../../base/restful_api_viewmodel.dart';
import '../../../configs/constants.dart';
import '../models/product_model.dart';
import '../models/product_store_model.dart';

class VoucherDetailViewModel extends RestfulApiViewModel {
  final int productId;
  VoucherDetailViewModel({required this.productId});
  var stores = RxList<ProductStoreModel>();
  var product = Rxn<ProductModel>();
  var isLoading = false.obs;
  var liked = false.obs;
  void Function(String message)? onShowAlertError;
  var quantity = 1.obs;

  @override
  void onInit() {
    super.onInit();
    _getProductDetail();
    _getProductStores();
  }

  Future<void> toggleFavorite() async {
    final value = product.value;
    if (value == null) return;
    try {
      if (value!.liked == true) {
        await client.unlikeProduct(value?.likeId ?? 0);
        value?.likeId = 0;
        liked.value = false;
      } else {
        final response = await client.likeProduct(productId);
        value?.likeId = response.data?.id;
        liked.value = (response.data?.id ?? 0) != 0;
      }
    } catch (error) {
      onShowAlertError?.call("Error toggling favorite: $error");
      print("Error toggling favorite: $error");
    }
  }

  Future<void> _getProductDetail() async {
    if (isLoading.value) return;
    try {
      isLoading.value = true;
      final response = await client.getProduct(productId);
      product.value = response.data;
      liked.value = product.value?.liked == true;
    } catch (error) {
      onShowAlertError?.call("Error fetching product detail: $error");
      print("Error fetching product detail: $error");
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> _getProductStores() async {
    try {
      final response = await client.getProductStores(productId);
      stores.value = response.data ?? [];
    } catch (error) {
      onShowAlertError?.call("Error product stores: $error");
      print("Error product stores: $error");
    } finally {}
  }

  verifyOrderProduct() async {
    final value = product.value;
    var body = {
      "product_id": productId,
      "price": value?.amountToBePaid,
      "quantity": quantity.value,
    };
    if (value?.previewFlashSale?.isFlashSalePrice == true) {
      final flashSaleId = value?.previewFlashSale?.id;
      if (flashSaleId != null) {
        body["flash_sale_id"] = flashSaleId;
      }
    }
    showLoading();
    client.verifyOrderProduct(body).then((value) {
      hideLoading();
      if (!value.isSuccess) {
        onShowAlertError?.call(value.errorMessage ?? Constants.commonError);
      } else {
        onShowAlertError?.call("Verify Order Product Success -> Go To Payment Detail");
      }
    });
  }
}
