import 'dart:async';
import 'package:flutter/cupertino.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/networking/restful_api_client_all_request.dart';
import '../../../base/base_response_model.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;
  final RxList<ProductModel> 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;
  /// Đánh dấu đã hoàn tất lần tải đầu tiên (có dữ liệu) để UI có thể bắt đầu countdown
  final firstLoadDone = false.obs;
  void Function(BaseResponseModel<SubmitViewVoucherCompletedResponse> response)? submitCampaignViewVoucherResponse;
  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);
  }

  @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 _callProductApi((api) => api.productsCustomerLikes(body));
      final fetchedData = result.data ?? [];
      if (fetchedData.isEmpty || fetchedData.length < _pageSize) {
        _hasMore = false;
      }
      products.addAll(fetchedData);
    } catch (error) {
      debugPrint("Error fetching products: $error");
    } finally {
      hideLoading();
      isLoading.value = false;
      isLoadMore.value = false;
      // Khi lần đầu có dữ liệu, đánh dấu để UI start countdown
      if (products.isNotEmpty) firstLoadDone.value = 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;
    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 _callProductApi((api) => api.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) {
      debugPrint("Error fetching products: $error");
    } finally {
      hideLoading();
      isLoading.value = false;
      isLoadMore.value = false;
      // Khi lần đầu có dữ liệu, đánh dấu để UI start countdown
      if (products.isNotEmpty) firstLoadDone.value = true;
    }
  }

  void submitCampaignViewVoucherComplete() async {
    showLoading();
    final response = await client.submitCampaignViewVoucherComplete();
    hideLoading();
    submitCampaignViewVoucherResponse?.call(response);
  }
}
