
import 'package:dio/dio.dart';
import '../general/search_bar.dart';
import 'package:flutter/material.dart';

import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/business.dart';
import '../../models/product.dart';
import '../../pages/product_detail_page.dart';
import '../../store/actions.dart';
import '../../store/store.dart';
import '../../utils/http_util.dart';
import '../../utils/utils.dart';
import '../../widgets/mobile/mobile_product_item.dart';

class MobileStoreProductSearch extends StatefulWidget {
  final Key? key;
  final Business business;

  const MobileStoreProductSearch(this.business, {this.key});

  @override
  State<StatefulWidget> createState() {
    return MobileStoreProductSearchState();
  }

}

class MobileStoreProductSearchState extends State<MobileStoreProductSearch> {

  int page = 1;
  int numPerPage = 10;
  int lastResultSize = 0;
  double lastBottomPosition = 0;
  String lastKeyword = '';

  SearchBarController _controller = SearchBarController<Product>();

  @override
  Widget build(BuildContext context) {
    store.dispatch(UpdateContext(context));

    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        child: NotificationListener<ScrollNotification>(
          child: SearchBar(
            searchBarController: _controller,
            minimumChars: 2,
            hintText: S.of(context).enter_product_keyword,
            cancellationWidget: Text(
              S.of(context).cancel,
            ),
            onSearch: search,
            onItemFound: (Product searchProduct, int index) {
              return MobileProductItem(
                product: searchProduct,
                business: widget.business,
              );
            },
            onError: (error) {
              return Center(
                child: Text("$error"),
              );
            },
            emptyWidget: Center(
              child: Text(
                S.of(context).empty_result_change_keyword,
              ),
            ),
          ),
          onNotification: (notification) {
            if (notification.metrics.atEdge) {
              print('fff: $page, $lastBottomPosition, ${notification.metrics.pixels}');
              if (page != 0 && lastResultSize >= numPerPage && notification.metrics.pixels != 0) {
                if (notification.metrics.pixels > lastBottomPosition) {
                  lastBottomPosition = notification.metrics.pixels;
                  page += 1;
                  _controller.replayLastSearch();
                }
              }
            }
            return true;
          },
        ),
      ),
    );
  }

  Future<List<Product>> search(String keyword) async {
    if (lastKeyword != keyword) {
      page = 1;
    }
    lastKeyword = keyword;
    var result = await HttpUtil.httpGet('v1/search-store-product2',
      queryParameters: {
        'store_id': widget.business.id,
        'keyword': keyword,
        'page': page,
        'num_per_page': numPerPage,
      },
      returnError: true,
    );
    if (result is DioError) {
      if (result.response != null) {
        throw RuntimeError(result.response.data);
      } else {
        throw RuntimeError(result.message);
      }
    } else if (result != null && result is List) {
      lastBottomPosition = 0;
      var r = result.map((e) => Product.fromJson(e)).toList();
      lastResultSize = r.length;
      if (lastResultSize < numPerPage) {
        page = 1;
      }
      return r;
    }
    return [];
  }

  @override
  void initState() {
    super.initState();
    eventBus.on<OnCartInfoUpdated>().listen((event) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  void _showProductDetail(Product p) {
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => ProductDetailPage(
            product: p,
            business: widget.business,
          )),
    );
  }
}