

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import '../../utils/utils.dart';
import '../../widgets/desktop/shop_products.dart';
import '../../widgets/general/bottom_nav.dart';
import '../../widgets/general/breadcrumbs.dart';
import '../../widgets/general/navigationbar.dart';
import '../../widgets/general/sliding_up_panel.dart';
import '../../widgets/mobile/shopping_cart_bar.dart';
import 'shop_bulletin.dart';

import '../../constants.dart';
import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/business.dart';
import '../../models/category_products.dart';
import 'product_search.dart';
import 'shop_promote.dart';
import 'shopping_cart_widget.dart';

class Shop extends StatefulWidget {
  final int businessId;

  const Shop({Key? key, this.businessId}): super(key: key);

  @override
  State<StatefulWidget> createState() => ShopState();

}

class ShopState extends State<Shop> {
  Business _business;

  PanelController panelController = PanelController();
  SlidingUpPanel _slidUpShoppingCart;
  GlobalKey endKey = GlobalKey();

  List<CategoryProducts> _categoryProducts;
  bool displayProductByCategoryClick = false;
  String displayProductByCategoryClickIndicator = '';
  int categoryId = 0;
  static int _productCurrentPage = 1;

  int _categoryIndex = 0;
  bool _categoryIndexChange = false;
  bool _isLoading = false;

  dynamic data;

  @override
  Widget build(BuildContext context) {
    if (_business == null) {
      return Scaffold(
        body: Center(
          child: SpinKitWave(
            color: Colors.lightBlueAccent,
            size: 40.0,
          ),
        ),
      );
    }

    _slidUpShoppingCart = SlidingUpPanel(
      controller: panelController,
      minHeight: 0.0,
      maxHeight: 250.0,
      isDraggable: false,
      backdropEnabled: true,
      slideDirection: SlideDirection.DOWN,
      panel: ShoppingCartBar(
        business: _business,
        endKey: endKey,
        barAtBottom: true,
        hasPicture: true,
        onEmptyCartListener: () {
          Future.delayed(Duration(seconds: 1), () {
            panelController.close();
          });
        },
        onPanelOpenCloseRequest: () {
          if (panelController.isPanelOpen) {
            panelController.close();
          } else {
            panelController.open();
          }
        },
      ),
    );

    Scaffold scaffold = Scaffold(
      appBar: MiniNavigationBar(
        title: S.of(context).shop,
        back: true,
        breadCrumbs: [
          BreadCrumb(S.of(context).shop, null),
          BreadCrumb(null, null,
            item: Container(
              margin: EdgeInsets.only(left: 20.0),
              child: Row(
                children: [
                  Container(
                    child: Icon(
                      Icons.search,
                      size: 24,
                      color: Colors.blue,
                    ),
                  ),
                  Container(
                    child: Text(
                      S.of(context).search_product,
                    ),
                  ),
                ],
              ),
            ),
            onTap: () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (BuildContext context) {
                    return ProductSearch(_business);
                  }));
            },
          ),
        ],
        breadCrumbHeight: Constants.BREADCRUMB_HEIGHT,
        shoppingCart: ShoppingCartWidget(
          business: _business,
          onTap: () {
            if (panelController.isPanelClosed) {
              panelController.open();
            }
          },
        ),
      ),
      body: Scrollbar(
        child: NotificationListener<ScrollNotification>(
          onNotification: (scrollNotification) {
            if (scrollNotification is ScrollEndNotification &&
                scrollNotification.metrics.pixels == scrollNotification.metrics.maxScrollExtent) {
              loadMoreProducts();
            }
            return false;
          },
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                ShopPromote(data),
                ShopBulletin(_business),
                ShopProducts(data),
              ],
            ),
          ),
        ),
      ),
      bottomNavigationBar: BottomNav(),
    );
    return Stack(
      children: [
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          child: scaffold,
        ),
        _slidUpShoppingCart,
      ],
    );
  }

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

        });
      }
    });
    eventBus.on<CategoryChangeEvent>().listen((event) {
      if (mounted) {
        // setState(() {
        //   categoryId = event.categoryId;
        //   _productCurrentPage = 1;
        // });
        categoryId = event.categoryId;
        _productCurrentPage = 1;
        _isLoading = true;
        Utils.showLoadingDialog(context, message: S.of(context).loading);
        loadProducts();
      }
    });
    loadProducts();
  }

  void loadProducts() {
    print('categoryId $categoryId');
    if (categoryId < 0) {
      return;
    }
    _productCurrentPage = 1;
    Utils.loadProducts(
        widget.businessId, categoryId, _productCurrentPage, false,
            (value) {
          if (_isLoading) {
            _isLoading = false;
            Navigator.of(context).pop();
          }
          if (mounted) {
            if (_business == null) {
              setState(() {
                displayProductByCategoryClick =
                value['display_product_by_category_click'];
                displayProductByCategoryClickIndicator = '';
                _business = Business.fromJson(value['business']);
                _categoryProducts = (value['category_products'] as List)
                    .map((i) => CategoryProducts.fromJson(i))
                    .toList();
                if (categoryId == 0 && displayProductByCategoryClick) {
                  categoryId = _categoryProducts[0].id;
                }
                data = value;
              });
            } else {
              eventBus.fire(GetCategoryProducts(value));
            }
          }
        },
            (error) {
          print('error: $error');
          if (_isLoading) {
            _isLoading = false;
            Navigator.of(context).pop();
          }
          if (mounted) {
            setState(() {});
          }
          Utils.showMessageDialog(context, error);
        }, featuredCount: 6, hotSaleCount: 0, keyword: ''
    );
  }

  void loadMoreProducts() {
    if (_productCurrentPage == 0 || categoryId <= 0) {
      return;
    }
    _productCurrentPage += 1;
    Utils.loadProducts(widget.businessId, categoryId, _productCurrentPage, true, (value) {
          if (_isLoading) {
            _isLoading = false;
            Navigator.of(context).pop();
          }
          if (mounted) {
            List<CategoryProducts> moreCategoryProducts = (value as List).map((i) => CategoryProducts.fromJson(i)).toList();
            if (moreCategoryProducts.isEmpty) {
              _productCurrentPage = 0;
            } else {
              if (moreCategoryProducts[0].products.length < Constants.ORDERS_PER_PAGE) {
                _productCurrentPage = 0;
              }
            }
            eventBus.fire(MoreCategoryProducts(moreCategoryProducts));
          }
        }, (error) {
          print('error: $error');
          if (_isLoading) {
            _isLoading = false;
            Navigator.of(context).pop();
          }
          Utils.showMessageDialog(context, error);
        }
    );
  }

  int nextCategoryId(int currentCategoryId) {
    if (_categoryProducts.length <= 0) {
      return 0;
    }
    for (int i = 0; i < _categoryProducts.length; i++) {
      if (_categoryProducts[i].id == currentCategoryId) {
        try {
          CategoryProducts cps = _categoryProducts[i + 1];
          return cps.id;
        } catch (error) {
          print('Error $error');
        }
      }
    }
    return 0;
  }
}