import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import 'package:mypoint_flutter_app/screen/data_network_service/product_network_data_model.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../../configs/constants.dart';
import '../../preference/contact_storage_service.dart';
import '../../preference/point/point_manager.dart';
import '../voucher/models/product_brand_model.dart';
import '../voucher/models/product_model.dart';
import '../voucher/models/product_type.dart';

class DataNetworkServiceViewModel extends RestfulApiViewModel {
  var histories = RxList<String>();
  final RxList<ProductBrandModel> topUpBrands = <ProductBrandModel>[].obs;
  final RxList<TopUpNetworkDataModel> topUpNetworkData = <TopUpNetworkDataModel>[].obs;
  final Map<String, List<TopUpNetworkDataModel>> _allValue = {};

  var selectedBrand = Rxn<ProductBrandModel>();
  var selectedProduct = Rxn<ProductNetworkDataModel>();
  var phoneNumber = ''.obs;
  void Function(String message)? onShowAlertError;
  void Function(String message)? onShowAlertRedeemSuccess;

  int get payPoint {
    return (int.tryParse(selectedProduct.value?.prices?.firstOrNull?.payPoint ?? "0") ?? 0);
  }
  bool get isValidBalance {
    return UserPointManager().point >= payPoint;
  }

  bool validatePhoneNumber() {
    final phone = phoneNumber.value.replaceAll(RegExp(r'\s+'), '');
    final regex = RegExp(r'^(0|\+84)(3[2-9]|5[6|8|9]|7[0|6-9]|8[1-5]|9[0-4|6-9])[0-9]{7}$');
    return regex.hasMatch(phone);
  }

  @override
  void onInit() {
    super.onInit();
    final myPhone = DataPreference.instance.phone ?? '';
    phoneNumber.value = myPhone;
    ContactStorageService().getUsedContacts().then((value) {
      if (value.isNotEmpty) {
        histories.value = value;
      } else {
        histories.value = [myPhone];
      }
    });
    if (!histories.contains(myPhone)) {
      histories.value.insert(0, myPhone);
      ContactStorageService().saveUsedContact(myPhone);
    }
  }

  firstLoadNetworkData() async {
    _getNetworkBrands();
  }

  _getNetworkBrands() {
    showLoading();
    client.productTopUpBrands().then((response) {
      topUpBrands.value = response.data ?? [];
      hideLoading();
      checkMobileNetwork();
    }).catchError((error) {
      hideLoading();
      print('Error fetching brands topup: $error');
    });
  }

  checkMobileNetwork() {
    showLoading();
    client.checkMobileNetwork(phoneNumber.value).then((response) {
      final brandCode = response.data?.brand ?? '';
      final brand = topUpBrands.isNotEmpty
          ? topUpBrands.firstWhere(
            (brand) => brand.code == brandCode,
        orElse: () => topUpBrands.first,
      ) : null;
      selectedBrand.value = brand;
      hideLoading();
      getTelcoDetail();
    }).catchError((error) {
      final first = topUpBrands.value.firstOrNull;
      if (first != null) {
        selectedBrand.value = first;
      }
      hideLoading();
      getTelcoDetail();
      print('Error checking mobile network: $error');
    });
  }

  Future<void> getTelcoDetail({String? selected}) async {
    final id = selectedBrand.value?.id;
    final code = selectedBrand.value?.code;
    if (id == null && code == null) return;

    void makeSelected(List<TopUpNetworkDataModel> data) {
      bool didSelect = false;
      final list = data
          .expand((e) => e.products ?? [])
          .toList();
      if (selected != null && selected.isNotEmpty) {
        for (var item in list) {
          final isMatch = item == int.tryParse(selected);
          if (isMatch) {
            selectedProduct.value = item;
            didSelect = true;
          }
        }
      }
      if (!didSelect && selectedProduct.value == null) {
        selectedProduct.value = list.firstOrNull;
      }
    }
    // Dùng cache nếu có
    if (_allValue.containsKey(code)) {
      final cached = _allValue[code]!;
      topUpNetworkData.value = cached;
      makeSelected(cached);
      return;
    }
    showLoading();
    try {
      final result = await client.getNetworkProducts((id ?? 0).toString());
      var data = result.data ?? [];
      data = data
          .where((e) => e.products?.isNotEmpty == true)
          .toList();
      _allValue[code ?? ""] = data;
      topUpNetworkData.value = data;
      makeSelected(data);
      hideLoading();
    } catch (error) {
      print("Error fetching all products: $error");
      hideLoading();
    }
  }

  redeemProductMobileCard() async {
    final id = selectedProduct.value?.id;
    if (id == null) {
      onShowAlertError?.call("Vui lòng chọn sản phẩm");
      return;
    }
    showLoading();
    try {
      final response = await client.redeemProductTopUps(id, phoneNumber.value);
      hideLoading();
      if (!response.isSuccess) {
        onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
        return;
      }
      final mgs = (response.errorMessage ?? "").isEmpty ? "Chúc mừng bạn đã đổi Ưu đãi data thành công" : (response.errorMessage ?? "");
      onShowAlertRedeemSuccess?.call(mgs);
    } catch (error) {
      hideLoading();
      onShowAlertError?.call(error.toString());
      return;
    }
  }
}