import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/invoice/invoice_shipment_list.dart';
import 'package:fcs/pages/invoice/model/invoice_model.dart';
import 'package:fcs/pages/widgets/local_popup_menu_button.dart';
import 'package:fcs/pages/widgets/local_popupmenu.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'invoice_list_row.dart';

class InvoiceList extends StatefulWidget {
  final bool forCustomer;

  const InvoiceList({Key key, this.forCustomer}) : super(key: key);
  @override
  _InvoiceListState createState() => _InvoiceListState();
}

class _InvoiceListState extends State<InvoiceList> {
  bool _isLoading = false;
  var _controller = ScrollController();

  @override
  void initState() {
    super.initState();
    _controller.addListener(() async {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        Provider.of<InvoiceModel>(context, listen: false)
            .loadMore(isCustomer: widget.forCustomer);
      }
    });

    InvoiceModel invoiceModel =
        Provider.of<InvoiceModel>(context, listen: false);
    invoiceModel.initData(widget.forCustomer, true, false);
  }

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

  @override
  Widget build(BuildContext context) {
    var invoiceModel = Provider.of<InvoiceModel>(context);

    final popupMenu = LocalPopupMenuButton(
      popmenus: [
        LocalPopupMenu(
            id: 1,
            textKey: "invoice.popupmenu.issused",
            selected: invoiceModel.selectedIndex == 1),
        LocalPopupMenu(
            id: 2,
            textKey: "invoice.popupmenu.paid",
            selected: invoiceModel.selectedIndex == 2),
        LocalPopupMenu(
            id: 3,
            textKey: "invoice.popupmenu.cancel",
            selected: invoiceModel.selectedIndex == 3)
      ],
      popupMenuCallback: (p) => this.setState(() {
        invoiceModel.selectedIndex = p.id;
        if (p.id == 2) {
          Provider.of<InvoiceModel>(context, listen: false)
              .initData(widget.forCustomer, false, true);
        } else if (p.id == 3) {
          Provider.of<InvoiceModel>(context, listen: false)
              .initData(widget.forCustomer, true, false);
        } else {
          Provider.of<InvoiceModel>(context, listen: false)
              .initData(widget.forCustomer, true, false);
        }
      }),
    );

    return LocalProgress(
      inAsyncCall: _isLoading,
      child: DefaultTabController(
        length: 2,
        child: Scaffold(
            appBar: AppBar(
              centerTitle: true,
              leading: new IconButton(
                icon: new Icon(CupertinoIcons.back),
                onPressed: () => Navigator.of(context).pop(),
              ),
              backgroundColor: primaryColor,
              title: LocalText(context, 'invoices.title',
                  color: Colors.white, fontSize: 20),
              actions: <Widget>[popupMenu],
            ),
            floatingActionButton: widget.forCustomer
                ? null
                : FloatingActionButton.extended(
                    onPressed: () {
                      _newInvoice();
                    },
                    icon: Icon(Icons.add),
                    label:
                        LocalText(context, 'invoices.add', color: Colors.white),
                    backgroundColor: primaryColor,
                  ),
            body: Column(
              children: <Widget>[
                Expanded(
                  child: RefreshIndicator(
                    child: ListView.separated(
                        physics: AlwaysScrollableScrollPhysics(),
                        controller: _controller,
                        separatorBuilder: (context, index) => Divider(
                              color: Colors.black,
                              height: 1,
                            ),
                        scrollDirection: Axis.vertical,
                        shrinkWrap: true,
                        itemCount: invoiceModel.invoices.length,
                        itemBuilder: (BuildContext context, int index) {
                          return InvoiceListRow(
                            key: ValueKey(invoiceModel.invoices[index].id),
                            invoice: invoiceModel.invoices[index],
                            forCustomer: widget.forCustomer,
                          );
                        }),
                    onRefresh: () => invoiceModel.refresh(),
                  ),
                ),
                invoiceModel.isLoading
                    ? Container(
                        padding: EdgeInsets.all(8),
                        color: primaryColor,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text("Loading...",
                                style: TextStyle(color: Colors.white)),
                          ],
                        ),
                      )
                    : Container(),
              ],
            )),
      ),
    );
  }

  _newInvoice() async {
    Navigator.of(context)
        .push(CupertinoPageRoute(builder: (context) => InvoiceShipmentList()));
  }
}
