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

import '../../constants.dart';
import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/business.dart';
import '../../models/cart_info.dart';
import '../../models/category_products.dart';
import '../../store/store.dart';
import '../../utils/utils.dart';
import '../../widgets/desktop/product_item.dart';

class ShopProducts extends StatefulWidget {
  final dynamic data;

  const ShopProducts(this.data, {Key? key}): super(key: key);

  @override
  State<StatefulWidget> createState() => ShopProductsState();
}

class ShopProductsState extends State<ShopProducts> {
  double sideSpace = 0;
  double mainSpace = 1200;

  dynamic data;

  static const num _categoryHeight = 50.0;
  static const num _categoryDescHeight = 50.0;
  static const num _productHeight = 266.0;

  bool displayProductByCategoryClick = false;
  String displayProductByCategoryClickIndicator = '';
  int categoryId = 0;
  double leftSideMenuWidth = 0;

  int _categoryIndex = 0;
  List<CategoryProducts> _categoryProducts = [];
  Business _business;

  double menuPosition = 0;

  ScrollController _menuScrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    if (MediaQuery.of(context).size.width <= 1200) {
      mainSpace = MediaQuery.of(context).size.width;
      sideSpace = 0;
    } else {
      mainSpace = 1200;
      sideSpace = (MediaQuery.of(context).size.width - 1200) / 2;
    }

    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: sideSpace,
          ),
          Expanded(
            child: Container(
              child:
              // Row(
              //   mainAxisAlignment: MainAxisAlignment.start,
              //   crossAxisAlignment: CrossAxisAlignment.start,
              //   mainAxisSize: MainAxisSize.min,
              //   children: [
              //     _buildCategories(),
              //     Expanded(
              //       child: _buildProducts(),
              //     ),
              //   ],
              // ),
              IntrinsicHeight(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    _buildCategories(),
                    Expanded(
                      child: _buildProducts(),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Container(
            width: sideSpace,
          ),
        ],
      ),
    );
  }

  Widget _buildCategories() {
    return new Container(
      width: leftSideMenuWidth,
      height: 500,
      color: new Color(0xFFF5F5F5),
      child: new SizedBox.expand(
        child: ListView.builder(
          physics: ClampingScrollPhysics(),
          controller: _menuScrollController,
          itemCount: _categoryProducts == null ? 0 : _categoryProducts.length,
          itemBuilder: (BuildContext context, int i) {
            CategoryProducts cp = _categoryProducts[i];
            int qtyInCategory = 0;
            CartInfo cartInfo = Utils.getCartInfoByBusiness(store.state.cartInfos, _business);
            if (cartInfo != null &&
                cartInfo.businessInfo.id == _business.id &&
                cartInfo.productList != null) {
              for (var i = 0; i < cartInfo.productList.length; i++) {
                if (cartInfo.productList[i].product.categoryId == cp.id) {
                  qtyInCategory += cartInfo.productList[i].quantity.ceil();
                }
              }
            }
            Row categoryRow = Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[],
            );
            categoryRow.children.add(
              Expanded(
                flex: 1,
                child: Container(
                  margin: EdgeInsets.only(top: 5.0, bottom: 5.0),
                  child: Text(
                    cp.name,
                    style: TextStyle(
                        fontSize: 13.0,
                        fontWeight: (cp.id == Constants.FEATURED_PRODUCT_ID ||
                            cp.id == Constants.HOT_SALE_ID)
                            ? FontWeight.bold
                            : FontWeight.normal,
                        color: (cp.id == Constants.HOT_SALE_ID)
                            ? Colors.redAccent
                            : ((cp.id == Constants.FEATURED_PRODUCT_ID)
                            ? Colors.lightGreen
                            : Colors.black87)),
//                    overflow: kIsWeb ? null : TextOverflow.ellipsis,
                    overflow: TextOverflow.ellipsis,
                    softWrap: true,
                    maxLines: 2,
                  ),
                ),
              ),
            );
            if (qtyInCategory > 0) {
              categoryRow.children.add(
                Badge(
                  badgeContent: Text(
                    '$qtyInCategory',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 11.0,
                    ),
                  ),
                  animationType: BadgeAnimationType.scale,
                ),
              );
            } else {
              categoryRow.children.add(SizedBox.shrink());
            }
            return GestureDetector(
              child: new Container(
                height: 70.0,
                padding: new EdgeInsets.symmetric(horizontal: 10.0),
                decoration: new BoxDecoration(
                    color: cp.id == categoryId ? Colors.white : null,
                    border: new Border(
                        bottom:
                        new BorderSide(color: new Color(0xFFEBEBEB)))),
                child: categoryRow,
              ),
              onTap: () => _selectCategory(cp.id),
            );
          }
        ),
      ),
    );
  }

  void _selectCategory(int i) {
    categoryId = i;
    eventBus.fire(CategoryChangeEvent(i));
  }

  Widget _buildProducts() {
    if (_categoryProducts == null) {
      return SizedBox.shrink();
    }
    Column col = new Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[],
    );
    for (int i = 0; i < _categoryProducts.length; i++) {
      CategoryProducts cp = _categoryProducts[i];
      if (cp.products.length > 0) {
        col.children.add(new Container(
            height: _categoryDescHeight,
            padding: new EdgeInsets.symmetric(horizontal: 10.0),
            color: new Color(0xFFF5F5F5),
            child: new Row(
              children: <Widget>[
                new Expanded(
                    child: new Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      textBaseline: TextBaseline.alphabetic,
                      children: <Widget>[
                        new Padding(
                          padding: new EdgeInsets.only(right: 5.0),
                          child: new Text(
                            cp.name,
                            style: new TextStyle(
                                fontSize: 16.0,
                                fontWeight:
                                (cp.id == Constants.FEATURED_PRODUCT_ID ||
                                    cp.id == Constants.HOT_SALE_ID)
                                    ? FontWeight.bold
                                    : FontWeight.normal,
                                color: (cp.id == Constants.HOT_SALE_ID)
                                    ? Colors.redAccent
                                    : ((cp.id ==
                                    Constants.FEATURED_PRODUCT_ID)
                                    ? Colors.lightGreen
                                    : Colors.black87)),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        new Visibility(
                            visible: cp.description.isNotEmpty,
                            child: new Text(
                              cp.description,
                              overflow: TextOverflow.ellipsis,
                              style: new TextStyle(
                                  fontSize: 10.0,
                                  color: new Color(0xFF999999)),
                            ),
                            replacement: const SizedBox.shrink()),
                      ],
                    ))
              ],
            )));

        var it = cp.products.iterator;
        for (int i = 0; i < cp.products.length; i++) {
          var r1 = Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [],
          );
          double d = getProductCountInRow();
          int c = int.parse(d.toString());
          while (d > 0) {
            if (it.moveNext()) {
              r1.children.add(
                Container(
                  width: (mainSpace - leftSideMenuWidth) / c - 4.0,
                  margin: EdgeInsets.only(top: 2.0, bottom: 2.0, left: 2.0, right: 2.0),
                  child: ProductItem(
                    it.current,
                    _business,
                  ),
                ),
              );
            }
            d -= 1;
          }
          col.children.add(r1);
        }

        if (displayProductByCategoryClick) {
          if (displayProductByCategoryClickIndicator.isNotEmpty) {
            col.children.add(
              Container(
                padding: EdgeInsets.all(12.0),
                child: Center(
                  child: Text(
                    displayProductByCategoryClickIndicator,
                    style: TextStyle(
                      color: Colors.black54,
                    ),
                  ),
                ),
              ),
            );
          } else if (categoryId > 0) {
            if (cp.products.length < Constants.ORDERS_PER_PAGE) {
              col.children.add(
                Container(
                  padding: EdgeInsets.all(12.0),
                  child: Center(
                    child: Text(
                      S
                          .of(context)
                          .end_of_the_list,
                      style: TextStyle(
                        color: Colors.black54,
                      ),
                    ),
                  ),
                ),
              );
            } else {
              col.children.add(
                Container(
                  padding: EdgeInsets.all(12.0),
                  child: Center(
                    child: Text(
                      S
                          .of(context)
                          .pull_up_to_load_more,
                      style: TextStyle(
                        color: Colors.black54,
                      ),
                    ),
                  ),
                ),
              );
            }
          }
        }
      }
    }
    return col;
  }

  void loadData() {
    // _categoryProducts .clear();
    _categoryProducts = (data['category_products'] as List)
        .map((i) => CategoryProducts.fromJson(i))
        .toList();
    _business = Business.fromJson(data['business']);
    displayProductByCategoryClick = data['display_product_by_category_click'];
    if (displayProductByCategoryClick) {
      leftSideMenuWidth = 200;
    }
    displayProductByCategoryClickIndicator = '';
    if (categoryId == 0 && displayProductByCategoryClick) {
      categoryId = _categoryProducts[0].id;
    }
    setState(() {

    });
  }

  @override
  void initState() {
    super.initState();
    data = widget.data;
    loadData();
    eventBus.on<GetCategoryProducts>().listen((event) {
      if (mounted) {
        data = event.data;
        loadData();
      }
    });
    eventBus.on<MoreCategoryProducts>().listen((event) {
      if (mounted) {
        setState(() {
          List<CategoryProducts> moreCategoryProducts = event.data;
          if (moreCategoryProducts.isEmpty) {
            displayProductByCategoryClickIndicator = S
                .of(context)
                .end_of_the_list;
          } else {
            if (moreCategoryProducts[0].products.length <
                Constants.ORDERS_PER_PAGE) {
              displayProductByCategoryClickIndicator = S
                  .of(context)
                  .end_of_the_list;
            } else {
              displayProductByCategoryClickIndicator =
                  S
                      .of(context)
                      .pull_up_to_load_more;
            }
            CategoryProducts currentCp =
            getCategoryProductByCategoryId(categoryId);
            if (currentCp != null) {
              currentCp.products.addAll(moreCategoryProducts[0].products);
            } else {
              displayProductByCategoryClickIndicator = S
                  .of(context)
                  .end_of_the_list;
            }
          }
        });
      }
    });
  }

  int numCategoriesHasProducts() {
    int num = 0;
    for (CategoryProducts cp in _categoryProducts) {
      if (cp.products.length > 0) {
        num += 1;
      }
    }
    return num;
  }

  CategoryProducts getCategoryProductByCategoryId(int cid) {
    for (CategoryProducts cp in _categoryProducts) {
      if (cp.id == cid) {
        return cp;
      }
    }
    return null;
  }

  double getProductCountInRow() {
    double d = 2;
    if (mainSpace >= 800 && mainSpace < 1000) {
      d = 3;
    } else if (mainSpace >= 1000) {
      d = 4;
    }
    return d;
  }
}