
import 'package:flutter/material.dart';
import 'package:flutter_wisetronic/events/eventbus.dart';
import 'package:flutter_wisetronic/events/events.dart';
import 'package:flutter_wisetronic/generated/l10n.dart';
import 'package:flutter_wisetronic/models/order.dart';
import 'package:flutter_wisetronic/pages/order_detail.dart';
import 'package:flutter_wisetronic/store/actions.dart';
import 'package:flutter_wisetronic/store/store.dart';
import 'package:flutter_wisetronic/utils/double_back_to_close_app.dart';
import 'package:flutter_wisetronic/utils/http_util.dart';
import 'package:flutter_wisetronic/utils/utils.dart';
import '../../constants.dart';
import '../../routes.dart';
import '../../utils/util_web.dart' if (dart.library.io) '../../utils/util_io.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'MobileBottomNav.dart';

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

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

}

class MobileOrdersState extends State<MobileOrders> with SingleTickerProviderStateMixin {
  GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  List<Order> orders = [];

  int _page = 1;
  int _pageCount = 1;

  bool _isLoading = false;
  bool _loadingFinish = false;

  RefreshController _refreshController = RefreshController(initialRefresh: true);

  void _onRefresh() {
    _page = 1;
    if (orders != null) {
      orders.clear();
    } else {
      orders = [];
    }
    _refreshController.resetNoData();
    _loadData(true);
  }

  void _onLoadMore() {
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    if (_pageCount > _page) {
      _page += 1;
      _loadData(false);
    } else {
      _refreshController.loadNoData();
    }
  }

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

    Widget body = SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: WaterDropHeader(),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus mode){
          Widget footer;
          if(mode == LoadStatus.idle) {
            footer = Text(S.of(context).pull_up_to_load_more);
          } else if (mode == LoadStatus.loading) {
            footer = CircularProgressIndicator();
          } else if (mode == LoadStatus.failed) {
            footer = Text(S.of(context).load_failed_retry);
          } else if (mode == LoadStatus.canLoading) {
            footer = Text(S.of(context).release_to_load_more);
          } else if (mode == LoadStatus.noMore) {
            footer = Text(S.of(context).no_more_record);
          } else {
            footer = Text('...');
          }
          return Container(
            height: 55.0,
            child: Center(child: footer,),
          );
        },
      ),
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoadMore,
      child: _buildBody(),
    );

    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text(
          S.of(context).my_orders,
        ),
        centerTitle: true,
      ),
      body: DoubleBackToCloseApp(
        snackBar: SnackBar(
          content: Text(S.of(context).tap_back_again_to_exit),
        ),
        child: body,
      ),
      bottomNavigationBar: MobileBottomNav(currentIndex: 3,),
    );
  }

  Widget _buildBody() {

    return ListView.builder(
      itemCount: orders != null && orders.length > 0 ? orders.length : 1,
      itemBuilder: (BuildContext context, int position) {
        Order order;
        if (orders != null && orders.length > 0) {
          order = orders[position];
        }
        if (order == null) {
          return Container(
            padding: EdgeInsets.all(16.0),
            child: Center(
              child: Text(
                S.of(context).you_have_no_orders_yet,
              ),
            ),
          );
        }

        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;
          _refreshController.requestRefresh();
        });
      }
    });
  }

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

  _loadData(bool isRefresh) {
    _loadingFinish = false;
    HttpUtil.httpGet('v1/orders',
      queryParameters: {
        'expand': 'cart_info',
        'page': _page.toString(),
        'size': Constants.ORDERS_PER_PAGE.toString(),
      },
    ).then((data) {
//      Utils.jsonPrettyPrint(data);
      if (isRefresh) {
        _refreshController.refreshCompleted();
      } else {
        _refreshController.loadComplete();
      }

      if (int.parse(data['_meta']['currentPage'].toString()) >= int.parse(data['_meta']['pageCount'].toString())) {
        _loadingFinish = true;
      }
      if (_loadingFinish) {
        _refreshController.loadNoData();
      }
      _page = int.parse(data['_meta']['currentPage'].toString());
      _pageCount = int.parse(data['_meta']['pageCount'].toString());

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