import 'package:flutter/material.dart';
// import 'package:flutter_pagewise/flutter_pagewise.dart';
import 'package:get/get.dart';
import 'package:loader_overlay/src/overlay_controller_widget_extension.dart';

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

class WishlistController extends GetxController with StateMixin<List<WishlistModel>>, ScrollMixin {
  final wlState = WishlistState();

  @override
  void onInit() {
    debugPrint('WishlistController onInit');
    fetchProducts();
    super.onInit();
  }

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

  Future<void> fetchProducts() async {
    debugPrint('WishlistController fetchProducts: ');
    final Map<String, dynamic> params = {
      // 'locale': 'tr',
      // 'currency': 'TMT',
      'page': wlState.page,
      'limit': Constants.PAGE_SIZE,
      'pagination': true,
    };

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

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

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

  Future<void> onWishlistTapped(BuildContext context, int productId) async {
    debugPrint('onWishlistTapped $productId');

    context.loaderOverlay.show();
    final result = await WishlistApi.addRemove(productId);

    if (result) refreshList();

    context.loaderOverlay.hide();
  }

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

  void onSupportButtonTapped() {
    debugPrint('_onSupportButtonTapped');
  }

  Future<bool> onWillPopScope() async {
    Get.offNamedUntil(AppRoutes.DASHBOARD, (route) => false);
    return false;
  }

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

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