import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import 'package:uuid/uuid.dart';
import '../../../networking/restful_api_viewmodel.dart';
import '../../../configs/constants.dart';
import '../../../shared/router_gage.dart';
import '../models/product_model.dart';
import '../models/product_store_model.dart';

class VoucherDetailViewModel extends RestfulApiViewModel {
  final int? productId;
  final int? customerProductId;
  VoucherDetailViewModel({
    this.productId,
    this.customerProductId,
  });

  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;
  bool get isMyProduct => customerProductId != null;
  int? get _id => productId ?? product.value?.id;

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

  Future<void> toggleFavorite() async {
    if (_id == null) return;
    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(_id!);
        value?.likeId = response.data?.id;
        liked.value = (response.data?.id ?? 0) != 0;
      }
    } catch (error) {
      onShowAlertError?.call(Constants.commonError);
    }
  }

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

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

  verifyOrderProduct(Function verified) 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 {
        verified.call();
      }
    });
  }

  redeemProduct() {
    showLoading();
    final requestId = Uuid().v4();
    client
        .orderSubmitPayment(
          products: [product.value!],
          quantity: 1,
          requestId: requestId,
          point: product.value?.amountToBePaid ?? 0,
        )
        .then((value) {
          hideLoading();
          if (value.isSuccess && (value.data?.id ?? "").isNotEmpty) {
            Get.offNamed(
              transactionHistoryDetailScreen,
              arguments: {"orderId": value.data?.id ?? "", "canBack": false},
            );
          } else {
            onShowAlertError?.call(value.errorMessage ?? Constants.commonError);
          }
        });
  }
}
