import 'package:fcs/domain/constants.dart';
import 'package:fcs/domain/entities/carton.dart';
import 'package:fcs/domain/entities/invoice.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/carton/model/carton_model.dart';
import 'package:fcs/pages/invoice/editor/invoice_carton_table.dart';
import 'package:fcs/pages/invoice/invoice_table.dart';
import 'package:fcs/pages/invoice/model/invoice_model.dart';
import 'package:fcs/pages/invoice/widgets.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/rates/model/shipment_rate_model.dart';
import 'package:fcs/pages/widgets/display_text.dart';
import 'package:fcs/pages/widgets/fcs_icons.dart';
import 'package:fcs/pages/widgets/local_button.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:intl/intl.dart';
import 'package:provider/provider.dart';

class InvoiceInfo extends StatefulWidget {
  final Invoice invoice;
  final bool forCustomer;
  InvoiceInfo({this.invoice, this.forCustomer});

  @override
  _InvoiceInfoState createState() => _InvoiceInfoState();
}

class _InvoiceInfoState extends State<InvoiceInfo> {
  var dateFormatter = new DateFormat('dd MMM yyyy');

  Invoice _invoice;
  bool _isLoading = false;

  bool _showCartons = false;
  @override
  void initState() {
    super.initState();
    _invoice = widget.invoice;
    _invoice.shipments?.forEach((s) {
      s.isSelected = true;
    });
    _loadCartons();
  }

  _loadCartons() async {
    CartonModel cartonModel = Provider.of<CartonModel>(context, listen: false);
    List<Carton> cartons = [];
    for (var c in _invoice?.cartons ?? []) {
      var _carton = await cartonModel.getCarton(c.id);
      _carton.isChecked = true;
      cartons.add(_carton);
    }
    setState(() {
      _invoice.cartons = cartons;
    });
  }

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

  @override
  Widget build(BuildContext context) {
    bool isCanceled = _invoice.status == invoice_cancel_status;
    bool isPaid = _invoice.status == invoice_paid_status;
    var rateModel = Provider.of<ShipmentRateModel>(context);
    var rate = rateModel.rate;

    final cartonTable = InvoiceCartonTable(
      cartons: _invoice.cartons,
      rate: rate,
    );

    final invoiceTableBox = InvoiceTable(
      invoice: _invoice,
      rate: rate,
      deliveryFeeSelected: (selected) {
        setState(() {
          if (selected) {
            _invoice.deliveryFee = rate.deliveryFee;
          } else {
            _invoice.deliveryFee = 0;
          }
        });
      },
      discountSelected: (discount) {
        setState(() {
          _invoice.discount = discount;
        });
      },
    );
    final toggleButtonsBox = ToggleButtons(
      color: Colors.black45,
      selectedColor: Colors.black45,
      disabledColor: Colors.grey,
      selectedBorderColor: primaryColor,
      borderColor: Colors.transparent,
      fillColor: Colors.transparent,
      highlightColor: Colors.black45,
      children: <Widget>[
        Icon(cartonIconData),
      ],
      onPressed: (int index) {
        setState(() {
          _showCartons = !_showCartons;
        });
      },
      isSelected: [_showCartons],
    );

    final headerBox = Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(dateFormatter.format(_invoice.invoiceDate)),
            SizedBox(
              height: 5,
            ),
            Text(_invoice?.userName ?? ""),
            Text(
              _invoice?.fcsID ?? "",
              style: TextStyle(fontSize: 12),
            )
          ],
        ),
        Spacer(),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            toggleButtonsBox,
          ],
        ),
      ],
    );
    final paymentMethodBox = DisplayText(
      labelTextKey: "invoice.payment_method",
      text: _invoice.paymentMethod.name,
    );

    final cancelBtn = LocalButton(
      textKey: "invoice.cancel.btn",
      callBack: _cancel,
    );

    return LocalProgress(
      inAsyncCall: _isLoading,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          leading: new IconButton(
            icon: new Icon(CupertinoIcons.back, color: primaryColor),
            onPressed: () => Navigator.of(context).pop(),
          ),
          backgroundColor: Colors.white,
          shadowColor: Colors.transparent,
          title: LocalText(context, 'invoice.form.title',
              color: primaryColor, fontSize: 20),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: <Widget>[
              getInvoiceStatus(context, _invoice),
              headerBox,
              _showCartons ? cartonTable : Container(),
              _showCartons
                  ? Divider(
                      color: primaryColor,
                      thickness: 2,
                    )
                  : Container(),
              invoiceTableBox,
              SizedBox(
                height: 10,
              ),
              paymentMethodBox,
              SizedBox(
                height: 10,
              ),
              isCanceled || isPaid || widget.forCustomer
                  ? Container()
                  : cancelBtn,
            ],
          ),
        ),
      ),
    );
  }

  _cancel() {
    showConfirmDialog(context, "invoice.cancel.confirm", _cancelInvoice);
  }

  _cancelInvoice() async {
    setState(() {
      _isLoading = true;
    });

    try {
      InvoiceModel invoiceModel =
          Provider.of<InvoiceModel>(context, listen: false);

      await invoiceModel.cancelInvoice(_invoice);
      Navigator.pop(context, true);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
