import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import 'package:mypoint_flutter_app/screen/voucher/models/product_type.dart';
import '../../base/base_response_model.dart';
import '../../networking/restful_api_viewmodel.dart';
import 'models/product_model.dart';

class VoucherTabViewModel extends RestfulApiViewModel {
  final RxList<ProductModel> hotProducts = <ProductModel>[].obs;
  final RxList<ProductModel> allProducts = <ProductModel>[].obs;
  final RxBool isLoadMore = false.obs;
  bool _productApiLoaded = false;

  Future<void> _ensureProductApiLoaded() async {
    if (_productApiLoaded) return;
    await product_api.loadLibrary();
    _productApiLoaded = true;
  }

  Future<BaseResponseModel<T>> _callProductApi<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
    await _ensureProductApiLoaded();
    final api = product_api.ProductApi(client);
    return fn(api);
  }

  bool get _isDataAvailable {
    return hotProducts.isNotEmpty || allProducts.isNotEmpty;
  }

  int _currentPage = 0;
  final int _pageSize = 20;
  bool _hasMore = true;
  bool get hasMore => _hasMore;

  Future<void> refreshData({bool isShowLoading = true}) async {
    if (isShowLoading && _isDataAvailable) return;
    if (isShowLoading) showLoading();
    await Future.wait([
      getHotProducts(),
      getAllProducts(reset: true),
    ]);
    if (isShowLoading) hideLoading();
  }

  Future<void> getHotProducts() async {
    final body = {
      "type": ProductType.voucher.value,
      "size": 10,
      "index": 0,
      "catalog_code": "HOT",
    };
    try {
      final result = await _callProductApi((api) => api.getProducts(body));
      hotProducts.value = result.data ?? [];
    } catch (error) {
      debugPrint("Error fetching hot products: $error");
    }
  }

  Future<void> getAllProducts({bool reset = false}) async {
    if (reset) {
      _currentPage = 0;
      _hasMore = true;
    } else {
      _currentPage = allProducts.length;
    }

    if (!_hasMore) return;

    final body = {
      "type": ProductType.voucher.value,
      "size": _pageSize,
      "index": _currentPage,
    };

    try {
      isLoadMore.value = true;
      final result = await _callProductApi((api) => api.getProducts(body));
      final fetchedData = result.data ?? [];
      if (fetchedData.isEmpty || fetchedData.length < _pageSize) {
        _hasMore = false;
      }
      if (reset) {
        allProducts.value = fetchedData;
      } else {
        allProducts.addAll(fetchedData);
      }
    } catch (error) {
      debugPrint("Error fetching all products: $error");
    } finally {
      isLoadMore.value = false;
    }
  }
}
