

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

import '../../constants.dart';
import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/order.dart';
import '../../pages/order_detail.dart';
import '../../routes.dart';
import '../../store/actions.dart';
import '../../store/store.dart';
import '../../utils/double_back_to_close_app.dart';
import '../../utils/http_util.dart';
import '../../utils/util_web.dart' if (dart.library.io) '../../utils/util_io.dart';
import '../../utils/utils.dart';
import '../../widgets/general/bottom_nav.dart';
import '../../widgets/general/breadcrumbs.dart';
import '../../widgets/general/navigationbar.dart';


class DesktopOrders extends StatefulWidget {
  final Key? key;
  const DesktopOrders({this.key});

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

}

class DesktopOrdersState extends State<DesktopOrders> with SingleTickerProviderStateMixin {
  GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  List<Order> orders;

  bool _isLoading = false;

  int _page = 1;
  int _pageCount = 1;

  double sideSpace = 0;
  double mainSpace = 1200;

  ScrollController scrollController = ScrollController();


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

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (store.state.user == null) {
        store.dispatch(UpdateRedirectRoute('/orders'));
        Routes.router.navigateTo(context, '/login', replace: true);
        return;
      }
    });

    if (orders == null) {
      return new Scaffold(
        body: Center(
          child: SpinKitWave(
            color: Colors.lightBlueAccent,
            size: 40.0,
          ),
        ),
      );
    }

    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;
    }

    Widget body = NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification scrollInfo) {
        if (!_isLoading && scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent) {
          if (_pageCount > _page) {
            setState(() {
              _page += 1;
              _isLoading = true;
            });
            _loadData();
            return true;
          }
        }
        return false;
      },
      child: _buildBody(),
    );

    return Scaffold(
      key: _scaffoldKey,
      appBar: MiniNavigationBar(
        title: S.of(context).blog,
        back: true,
        breadCrumbs: [
          BreadCrumb(S.of(context).my_orders, null),
        ],
        breadCrumbHeight: Constants.BREADCRUMB_HEIGHT,
      ),
      body: DoubleBackToCloseApp(
        snackBar: SnackBar(
          content: Text(S.of(context).tap_back_again_to_exit),
        ),
        child: Row(
          children: [
            Container(
              width: sideSpace,
            ),
            Expanded(
              child: body,
            ),
            Container(
              width: sideSpace,
            ),
          ],
        ),
      ),
      bottomNavigationBar: BottomNav(),
    );
  }

  Widget _buildBody() {

    return ListView.builder(
      controller: scrollController,
      itemCount: orders != null && orders.length > 0 ? orders.length + 1 : 1,
      itemBuilder: (BuildContext context, int position) {
        Order order;
        if (orders != null && orders.length > 0 && position < orders.length) {
          order = orders[position];
        }

        if (order == null && orders.length <= 0) {
          return Container(
            padding: EdgeInsets.all(16.0),
            child: Center(
              child: Text(
                S.of(context).you_have_no_orders_yet,
              ),
            ),
          );
        } else if (position >= orders.length) {
          if (_pageCount > _page) {
            return Container(
              padding: EdgeInsets.all(16.0),
              child: Center(
                child: SpinKitThreeBounce(
                  color: Colors.lightBlueAccent,
                  size: 40.0,
                ),
              ),
            );
          } else {
            return Container(
              padding: EdgeInsets.all(16.0),
              child: Center(
                child: Center(
                  child: Text(
                    S.of(context).no_more_record,
                  ),
                ),
              ),
            );
          }
        }

        Row row = Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[],
        );
        row.children.add(Expanded(
          child: Container(
            child: Text(
              order.cartInfo.productList[0].name,
              style: TextStyle(
                fontSize: 14.0,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ));
        if (order.cartInfo.productList.length > 1) {
          row.children.add(Container(
            child: Text(
              S.of(context).and_more_item_token(Utils.getProductLineInOrder(order.cartInfo)),
              style: TextStyle(
                fontSize: 12.0,
                color: Colors.black26,
              ),
            ),
          ));
        }
        row.children.add(Container(
          width: 80.0,
          alignment: Alignment.centerRight,
          child: Text(
            '\$${order.totalPrice.toStringAsFixed(2)}',
            style: TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.bold,
            ),
          ),
        ));

        Row row3 = Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            ElevatedButton(
              child: Text(
                S.of(context).detail,
              ),
              onPressed: () {
                Navigator.push(context, MaterialPageRoute(
                  builder: (BuildContext context) => OrderDetail(order.id, fromOrders: true,),
                ));
              },
            ),
          ],
        );
        if (order.status == Constants.STATUS_COMPLETE && !order.hasComment) {
          row3.children.add(
            Padding(
              padding: EdgeInsets.only(left: 10.0),
              child: ElevatedButton(
                child: Text(
                  S.of(context).comment,
                ),
                onPressed: () {
                  Routes.router.navigateTo(context, '/new-comment/${order.id}');
                },
              ),
            ),
          );
        }

        Row row2 = Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[],
        );
        if (order.paymentStatus != Constants.PAYMENT_STATUS_PAID) {
          row2.children.add(row3);
          if (order.paymentStatus != Constants.PAYMENT_STATUS_PAID
              && order.status != Constants.STATUS_CANCELLED
              && order.status != Constants.STATUS_COMPLETE) {
            row2.children.add(ElevatedButton(
              child: Text(
                S.of(context)
                    .pay_now,
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.redAccent,
              ),
              onPressed: () {
                Routes.router.navigateTo(context, '/paynow/${order.id}');
              },
            ));
          } else {
            row2.children.add(ElevatedButton(
              child: Text(
                S.of(context).order_again,
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: Theme.of(context).primaryColor,
              ),
              onPressed: () {
                Utils.orderAgain(context, order.cartInfo);
              },
            ));
          }
        } else {
          row2.children.add(row3);
          row2.children.add(ElevatedButton(
            child: Text(
              S.of(context).order_again,
              style: TextStyle(
                color: Colors.white,
              ),
            ),
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).primaryColor,
            ),
            onPressed: () {
              Utils.orderAgain(context, order.cartInfo);
            },
          ));
        }

        return Container(
          padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 16.0),
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(
                width: 10.0,
                color: Colors.black26,
              ),
            ),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Container(
                    child: Util.showImage('${order.cartInfo.businessInfo.picUrl}',
                      width: 32.0,
                      height: 32.0,
                      fit: BoxFit.fill,
                    ),
                  ),
                  Expanded(
                    child: GestureDetector(
                      child: Container(
                        margin: EdgeInsets.only(left: 5.0, right: 5.0),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              child: Text(
                                '${order.cartInfo.businessInfo.name}',
                                style: TextStyle(
                                  fontSize: 20.0,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            Container(
                              child: Text(
                                '#${order.orderNum} ${Utils.timestampToString(context, order.createdAt, withTime: true)}',
                                style: TextStyle(
                                  fontSize: 12.0,
                                  color: Colors.black26,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      onTap: () {
                        Navigator.push(context, MaterialPageRoute(
                          builder: (BuildContext context) => OrderDetail(order.id, fromOrders: true,),
                        ));
                      },
                    ),
                  ),
                  Container(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          child: Text(
                            '${Utils.getOrderStatus(context, order.status)}',
                            style: TextStyle(
                              fontSize: 15.0,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Container(
                          child: SizedBox.shrink(),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              Container(
                padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
                width: double.infinity,
                child: SizedBox(),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      width: 0.5,
                      color: Colors.black12,
                    ),
                  ),
                ),
              ),
              GestureDetector(
                child: Container(
                  margin: EdgeInsets.only(top: 10.0, bottom: 20.0),
                  child: row,
                ),
                onTap: () {
                  Navigator.push(context, MaterialPageRoute(
                    builder: (BuildContext context) => OrderDetail(order.id, fromOrders: true,),
                  ));
                },
              ),
              Container(
                child: row2,
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  void initState() {
    super.initState();

    _page = 1;
    _pageCount = 1;
    eventBus.on<OnOrderUpdated>().listen((event) {
      if (mounted) {
        setState(() {
          orders = null;
        });
      }
    });

    _loadData();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  _loadData() {
    HttpUtil.httpGet('v1/orders',
      queryParameters: {
        'expand': 'cart_info',
        'page': _page.toString(),
        'size': Constants.ORDERS_PER_PAGE.toString(),
      },
    ).then((data) {
//      Utils.jsonPrettyPrint(data);
      _page = int.parse(data['_meta']['currentPage'].toString());
      _pageCount = int.parse(data['_meta']['pageCount'].toString());

      if (mounted) {
        setState(() {
          _isLoading = false;
          if (orders == null) {
            orders = [];
          }
          orders.addAll((data['items'] as List).map((e) => Order.fromJson(e)).toList());
        });
      }
    }).catchError((error) {
      if(mounted) {
        setState(() {
          _isLoading = false;
        });
      }
      Utils.showMessageDialog(context, error);
    });
  }
}