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/topup/models/brand_network_model.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../../preference/contact_storage_service.dart';
import '../voucher/models/product_brand_model.dart';
import '../voucher/models/product_model.dart';
import '../voucher/models/product_type.dart';

class TopUpViewModel extends RestfulApiViewModel {
  var histories = RxList<String>();
  final RxList<ProductBrandModel> topUpBrands = <ProductBrandModel>[].obs;
  final RxList<ProductModel> products = <ProductModel>[].obs;
  var selectedBrand = Rxn<ProductBrandModel>();
  var selectedProduct = Rxn<ProductModel>();
  final Map<String, List<ProductModel>> _allValue = {};
  var phoneNumber = ''.obs;

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

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

  firstLoadTopUpData() async {
    _getTopUpBrands();
  }

  _getTopUpBrands() async {
    await callApi<List<ProductBrandModel>>(
      request: () => client.getTopUpBrands(ProductType.topupMobile),
      onSuccess: (data, _) {
        topUpBrands.value = data;
        checkMobileNetwork();
      },
      showAppNavigatorDialog: true,
    );
  }

  checkMobileNetwork() async {
    await callApi<BrandNameCheckResponse>(
      request: () => client.checkMobileNetwork(phoneNumber.value),
      onSuccess: (data, _) {
        final brandCode = data?.brand ?? '';
        var brand = topUpBrands.isNotEmpty
            ? topUpBrands.firstWhere(
              (brand) => brand.code == brandCode,
          orElse: () => topUpBrands.first,
        ) : topUpBrands.value.firstOrNull;
        selectedBrand.value = brand;
        getTelcoDetail();
      },
      showAppNavigatorDialog: true,
    );
  }

  Future<void> getTelcoDetail({String? selected}) async {
    final code = selectedBrand.value?.code;
    final id = selectedBrand.value?.id;
    if (code == null || id == null) return;
    void makeSelected(List<ProductModel> list) {
      bool didSelect = false;
      if (selected != null && selected.isNotEmpty) {
        for (var item in list) {
          final isMatch = item.id == int.tryParse(selected);
          if (isMatch) {
            selectedProduct.value = item;
            didSelect = true;
          }
        }
      }
      // Nếu chưa có item nào được chọn → mặc định chọn 100k
      if (!didSelect && selectedProduct.value == null) {
         final item100k = list.isNotEmpty
            ? list.firstWhere(
              (e) => e.amountToBePaid == 100000,
          orElse: () => list.first,
        ) : null;
        selectedProduct.value = item100k;
      }
    }
    // Dùng cache nếu có
    if (_allValue.containsKey(code)) {
      final cached = _allValue[code]!;
      products.value = cached;
      makeSelected(cached);
      return;
    }
    final body = {
      "type": ProductType.topupMobile.value,
      "size": 200,
      "index": 0,
      "brand_id": selectedBrand.value?.id ?? 0,
    };
    await callApi<List<ProductModel>>(
      request: () => client.getProducts(body),
      onSuccess: (data, _) {
        _allValue[code] = data;
        products.value = data;
        makeSelected(data);
      },
      showAppNavigatorDialog: true,
    );
  }
}