import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/screen/voucher/models/product_type.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 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 client.getProducts(body);
      hotProducts.value = result.data ?? [];
    } catch (error) {
      print("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 client.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) {
      print("Error fetching all products: $error");
    } finally {
      isLoadMore.value = false;
    }
  }
}