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 isLoading = false.obs;
  final RxBool isLoadMore = false.obs;

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

  @override
  void onInit() {
    super.onInit();
    refreshData();
  }

  Future<void> refreshData() async {
    isLoading.value = true;
    await Future.wait([
      getHotProducts(),
      getAllProducts(reset: true),
    ]);
    isLoading.value = false;
  }

  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;
      allProducts.clear();
    } 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;
      }
      allProducts.addAll(fetchedData);
    } catch (error) {
      print("Error fetching all products: $error");
    } finally {
      isLoadMore.value = false;
    }
  }
}