import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../app.dart';

import 'state.dart';

class ProductListController extends GetxController with StateMixin<List<ProductModel>>, ScrollMixin {
  final productState = ProductState();

  @override
  void onInit() {
    fetchProducts();

    super.onInit();
  }

  @override
  void dispose() {
    debugPrint('productController dispose');
    super.dispose();
  }

  void onBackIconTapped() {
    debugPrint('Back from ProductListPage');
    Get.back();
  }

  void reset() {
    productState.repositories.clear();
    productState.page = 1;
    productState.getFirstData = false;
    productState.lastPage.value = false;
    change(null, status: RxStatus.loading());
  }

  Future<void> fetchProducts() async {
    FilterController fc = Get.find();
    final queryParams = fc.state.filterableQueryParams;

    final Map<String, dynamic> params = {
      'currency': 'TMT',
      'locale': await getLocale(),
      'page': productState.page,
      'limit': Constants.PAGE_SIZE,
    };

    params.addAll(queryParams);

    await ProductApi.get(params).then(
      (result) {
        final bool emptyRepositories = result.isEmpty;
        if (!productState.getFirstData && emptyRepositories) {
          change(null, status: RxStatus.empty());
        } else if (productState.getFirstData && emptyRepositories) {
          productState.lastPage.value = true;
        } else {
          productState.getFirstData = true;
          productState.repositories.addAll(result);

          if (result.length < Constants.PAGE_SIZE) productState.lastPage.value = true;

          change(productState.repositories, status: RxStatus.success());
        }
      },
      onError: (err) {
        change(null, status: RxStatus.error(err.toString()));
      },
    );
  }

  Future<void> refreshList() async {
    debugPrint('onRefresh');
    reset();
    await fetchProducts();
  }

  @override
  Future<void> onEndScroll() async {
    if (!productState.lastPage.value) {
      productState.page += 1;
      await fetchProducts();
    }
  }

  @override
  Future<void> onTopScroll() async {
    debugPrint('onTopScroll');
  }
}
