import 'dart:async';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_request.dart';
import '../../../base/restful_api_viewmodel.dart';
import '../models/product_model.dart';
import '../models/product_type.dart';

class VoucherListViewModel extends RestfulApiViewModel {
  VoucherListViewModel({required this.isHotProduct});

  final bool isHotProduct;
  Timer? _debounce;
  var products = <ProductModel>[].obs;
  var isLoading = false.obs;
  var isLoadMore = false.obs;
  int _currentPage = 0;
  final int _pageSize = 20;
  bool _hasMore = true;
  bool get hasMore => _hasMore;
  String _searchQuery = '';
  String get searchQuery => _searchQuery;
  var totalResult = 0.obs;

  @override
  void onInit() {
    super.onInit();
    getProducts(reset: true);
  }

  @override
  void onClose() {
    _debounce?.cancel();
    super.onClose();
  }

  void onSearchChanged(String value) {
    if (_searchQuery == value) return;
    _searchQuery = value;
    _debounce?.cancel();
    _debounce = Timer(const Duration(seconds: 1), () {
      getProducts(reset: true);
    });
  }

  Future<void> getProducts({bool reset = false}) async {
    if (isLoading.value) return;
    if (reset) {
      _currentPage = 0;
      _hasMore = true;
      products.clear();
    } else {
      _currentPage = products.length;
    }
    if (!_hasMore) return;

    final body = {
      "type": ProductType.voucher.value,
      "size": _pageSize,
      "index": _currentPage,
      if (isHotProduct) "catalog_code": "HOT",
      if (_searchQuery.isNotEmpty) "keywords": _searchQuery,
      if (_searchQuery.isNotEmpty) "keyword": _searchQuery,
    };

    try {
      isLoading.value = true;
      isLoadMore.value = true;
      final result = await client.getSearchProducts(body);
      final fetchedData = result.data?.products ?? [];
      totalResult.value = result.data?.total ?? 0;
      if (fetchedData.isEmpty || fetchedData.length < _pageSize) {
        _hasMore = false;
      }
      products.addAll(fetchedData);
    } catch (error) {
      print("Error fetching products: $error");
    } finally {
      isLoading.value = false;
      isLoadMore.value = false;
    }
  }
}
