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

class VoucherListViewModel extends RestfulApiViewModel {
  VoucherListViewModel({required this.isHotProduct, this.isFavorite = false});
  final bool isFavorite;
  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();
    loadData(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), () {
      loadData(reset: true);
    });
  }

  Future<void> loadData({bool reset = false}) async {
    if (isFavorite) {
      await _getFavoriteProducts(reset: reset);
    } else {
      await _getProducts(reset: reset);
    }
  }

  Future<void> _getFavoriteProducts({bool reset = false}) async {
    if (isLoading.value) return;
    if (reset) {
      _currentPage = 0;
      _hasMore = true;
      products.clear();
    } else {
      _currentPage = products.length;
    }
    if (!_hasMore) return;
    if (reset) {
      showLoading();
    }
    final body = {"size": _pageSize, "index": _currentPage};
    try {
      isLoading.value = true;
      isLoadMore.value = true;
      final result = await client.productsCustomerLikes(body);
      final fetchedData = result.data ?? [];
      if (fetchedData.isEmpty || fetchedData.length < _pageSize) {
        _hasMore = false;
      }
      products.addAll(fetchedData);
    } catch (error) {
      print("Error fetching products: $error");
    } finally {
      hideLoading();
      isLoading.value = false;
      isLoadMore.value = false;
    }
  }

  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;
    if (reset) {
      showLoading();
    }
    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 {
      hideLoading();
      isLoading.value = false;
      isLoadMore.value = false;
    }
  }
}
