import 'package:fcs/domain/entities/box.dart';
import 'package:fcs/domain/entities/cargo.dart';
import 'package:fcs/domain/entities/pickup.dart';
import 'package:fcs/domain/vo/delivery_address.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/localization/app_translations.dart';
import 'package:fcs/pages/box/model/box_model.dart';
import 'package:fcs/pages/delivery_address/delivery_address_row.dart';
import 'package:fcs/pages/delivery_address/model/delivery_address_model.dart';
import 'package:fcs/pages/main/model/main_model.dart';
import 'package:fcs/pages/shipment/model/shipment_model.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/widgets/bottom_up_page_route.dart';
import 'package:fcs/pages/widgets/input_text.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:fcs/pages/widgets/multi_img_controller.dart';
import 'package:fcs/pages/widgets/multi_img_file.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import 'package:flutter/material.dart';

import 'pickup_box_editor.dart';

class ShipmentEditor extends StatefulWidget {
  final Shipment pickUp;
  ShipmentEditor({this.pickUp});

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

class _ShipmentEditorState extends State<ShipmentEditor> {
  var dateFormatter = new DateFormat('dd MMM yyyy');
  final numberFormatter = new NumberFormat("#,###");
  MultiImgController multiImgController = MultiImgController();

  TextEditingController _addressEditingController = new TextEditingController();
  TextEditingController _fromTimeEditingController =
      new TextEditingController();
  TextEditingController _toTimeEditingController = new TextEditingController();
  TextEditingController _noOfPackageEditingController =
      new TextEditingController();
  TextEditingController _weightEditingController = new TextEditingController();
  TextEditingController _recipientNameEditingController =
      new TextEditingController();
  TextEditingController _recipientPhoneEditingController =
      new TextEditingController();
  TextEditingController _recipientAddressEditingController =
      new TextEditingController();
  TextEditingController _pickupDate = new TextEditingController();
  TextEditingController _handlingFeeController = new TextEditingController();

  Shipment _pickUp;
  bool _isLoading = false;
  var now = new DateTime.now();
  bool isNew;
  DeliveryAddress _shippingAddress = new DeliveryAddress();

  int _currVal = 1;

  @override
  void initState() {
    super.initState();
    if (widget.pickUp != null) {
      isNew = false;
      _pickUp = widget.pickUp;
      _addressEditingController.text = _pickUp.address;
      _fromTimeEditingController.text = _pickUp.fromTime;
      _toTimeEditingController.text = _pickUp.toTime;
      _noOfPackageEditingController.text = _pickUp.numberOfPackage.toString();
      _weightEditingController.text = _pickUp.weight.toString();
      _pickupDate.text = dateFormatter.format(now);
      _handlingFeeController.text = numberFormatter.format(_pickUp.handlingFee);
      _currVal = _pickUp.radioIndex;

      var mainModel = Provider.of<MainModel>(context, listen: false);
      // _recipientNameEditingController.text = mainModel.recipient.name;
      // _recipientPhoneEditingController.text = mainModel.recipient.phoneNumber;
      // _recipientAddressEditingController.text =
      //     mainModel.recipient.shippingAddress;
    } else {
      isNew = true;
      List<Cargo> _cargoTypes = [
        Cargo(type: 'General Cargo', weight: 25),
        Cargo(type: 'Medicine', weight: 20),
        Cargo(type: 'Dangerous Cargo', weight: 30)
      ];
      _pickUp = Shipment(cargoTypes: _cargoTypes);
    }
    var shipmentModel =
        Provider.of<DeliveryAddressModel>(context, listen: false);
    _shippingAddress = shipmentModel.deliveryAddresses[1];
  }

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

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

    final fromTimeBox = InputText(
        labelTextKey: 'shipment.from',
        iconData: Icons.timer,
        controller: _fromTimeEditingController);

    final toTimeBox = InputText(
        labelTextKey: 'shipment.to',
        iconData: null,
        controller: _toTimeEditingController);

    final fromTimeBoxReadOnly = fcsInputReadOnly(
      'From',
      Icons.timer,
      controller: _fromTimeEditingController,
    );

    final toTimeBoxReadOnly = fcsInputReadOnly(
      'To',
      null,
      controller: _toTimeEditingController,
    );

    final pickupTime = Padding(
      padding: const EdgeInsets.only(left: 20.0),
      child: Row(
        children: <Widget>[
          Container(
            child: fromTimeBox,
            width: 120,
          ),
          Padding(
            padding: const EdgeInsets.only(left: 8.0),
            child: Text('-'),
          ),
          Container(
            padding: EdgeInsets.only(left: 20),
            child: toTimeBox,
            width: 120,
          ),
        ],
      ),
    );

    final pickupTimeReadOnly = Padding(
      padding: const EdgeInsets.only(left: 20.0),
      child: Row(
        children: <Widget>[
          SizedBox(height: 5),
          Container(
            child: fromTimeBoxReadOnly,
            width: 120,
          ),
          Padding(
            padding: const EdgeInsets.only(left: 8.0),
            child: Text('-'),
          ),
          Container(
            child: toTimeBoxReadOnly,
            width: 120,
          ),
        ],
      ),
    );

    final noOfPackageBoxReadonly = fcsInputReadOnly(
      'Number of Packages',
      Octicons.package,
      controller: _noOfPackageEditingController,
    );

    final requestDateBox = Container(
        child: InkWell(
      onTap: () {
        DatePicker.showDatePicker(
          context,
          showTitleActions: true,
          currentTime: _pickupDate.text == ""
              ? null
              : dateFormatter.parse(_pickupDate.text),
          minTime: DateTime.now(),
          maxTime: DateTime(2030, 12, 31),
          onConfirm: (date) {},
          locale: LocaleType.en,
        );
      },
      child: TextFormField(
        controller: _pickupDate,
        autofocus: false,
        cursorColor: primaryColor,
        style: textStyle,
        enabled: false,
        keyboardType: TextInputType.datetime,
        decoration: new InputDecoration(
            border: InputBorder.none,
            focusedBorder: InputBorder.none,
            labelText: AppTranslations.of(context).text("shipment.date"),
            // labelStyle: languageModel.isEng ? labelStyle : labelStyleMM,
            contentPadding:
                EdgeInsets.symmetric(vertical: 10.0, horizontal: 0.0),
            icon: Icon(
              Icons.date_range,
              color: primaryColor,
            )),
        validator: (value) {
          if (value.isEmpty) {
            return AppTranslations.of(context).text("do.form.date");
          }
          return null;
        },
      ),
    ));

    MainModel mainModel = Provider.of<MainModel>(context);
    var boxModel = Provider.of<BoxModel>(context);

    return LocalProgress(
      inAsyncCall: _isLoading,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          leading: new IconButton(
            icon: new Icon(Icons.close),
            onPressed: () => Navigator.of(context).pop(),
          ),
          backgroundColor: primaryColor,
          title: LocalText(context, "shipment.edit.title",
              fontSize: 18, color: Colors.white),
        ),
        body: Card(
          child: Column(
            children: <Widget>[
              Expanded(
                  child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: ListView(children: <Widget>[
                  Center(child: nameWidget("mainModel.customer.name")),
                  Center(child: nameWidget("mainModel.customer.phoneNumber")),
                  isNew
                      ? Container()
                      : Center(
                          child: Padding(
                            padding: const EdgeInsets.only(left: 10.0, top: 8),
                            child: Text(
                              '#P200304',
                              style: TextStyle(
                                  color: Colors.black87,
                                  fontSize: 14,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ),
                  widget.pickUp == null
                      ? Container()
                      : widget.pickUp.isCourier
                          ? Padding(
                              padding: const EdgeInsets.only(left: 15.0),
                              child: fcsInputReadOnly(
                                  "Handling Fee/Courier Fee",
                                  FontAwesomeIcons.moneyBill,
                                  controller: _handlingFeeController),
                            )
                          : Padding(
                              padding: const EdgeInsets.only(left: 15.0),
                              child: fcsInputReadOnly(
                                  "Handling Fee/Courier Fee",
                                  FontAwesomeIcons.moneyBill,
                                  controller: _handlingFeeController),
                            ),

                  ExpansionTile(
                    title: Text(
                      'Pickup/Drop-off',
                      style: TextStyle(
                          color: primaryColor, fontWeight: FontWeight.bold),
                    ),
                    children: <Widget>[
                      Container(
                        child: Wrap(
                          children: pickupModel.radioGroups
                              .map((t) => RadioListTile(
                                    title: Text("${t.text}"),
                                    groupValue: _currVal,
                                    activeColor: primaryColor,
                                    value: t.index,
                                    onChanged: (val) {
                                      setState(() {
                                        _currVal = val;
                                      });
                                    },
                                  ))
                              .toList(),
                        ),
                      ),
                    ],
                  ),
                  _currVal == 3
                      ? Container(
                          child: DeliveryAddressRow(
                            shippingAddress: DeliveryAddress(
                                fullName: 'FCS Office',
                                addressLine1: '154-19 64th Ave.',
                                addressLine2: 'Flushing',
                                city: 'NY',
                                state: 'NY',
                                phoneNumber: '+1 (292)215-2247'),
                          ),
                        )
                      : _currVal == 4
                          ? Container(
                              child: Column(
                              children: <Widget>[
                                Container(
                                  padding: EdgeInsets.only(
                                      top: 20, bottom: 15, right: 15),
                                  child: Align(
                                    alignment: Alignment.center,
                                    child: Container(
                                      width: 350,
                                      height: 40,
                                      child: FloatingActionButton.extended(
                                        materialTapTargetSize:
                                            MaterialTapTargetSize.shrinkWrap,
                                        onPressed: () {},
                                        icon: Icon(Icons.arrow_right),
                                        label: Text(
                                          'Visit courier websie for nearest drop-off',
                                          style: TextStyle(fontSize: 12),
                                        ),
                                        backgroundColor: primaryColor,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ))
                          : Container(),

                  ExpansionTile(
                    title: Text(
                      'Package Information',
                      style: TextStyle(
                          color: primaryColor, fontWeight: FontWeight.bold),
                    ),
                    children: <Widget>[
                      Column(
                        children: getBoxList(context, boxModel.boxes),
                      ),
                      Container(
                        padding:
                            EdgeInsets.only(top: 20, bottom: 15, right: 15),
                        child: Align(
                          alignment: Alignment.bottomRight,
                          child: Container(
                            width: 120,
                            height: 40,
                            child: FloatingActionButton.extended(
                              materialTapTargetSize:
                                  MaterialTapTargetSize.shrinkWrap,
                              icon: Icon(Icons.add),
                              onPressed: () {
                                Navigator.push(
                                  context,
                                  BottomUpPageRoute(PickupBoxEditor()),
                                );
                              },
                              label: Text(
                                'Add Package',
                                style: TextStyle(fontSize: 12),
                              ),
                              backgroundColor: primaryColor,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 10.0),
                    ],
                  ),
                  _currVal == 3 || _currVal == 4
                      ? Container()
                      : ExpansionTile(
                          title: Text(
                            'Pickup Location / Time',
                            style: TextStyle(
                                color: primaryColor,
                                fontWeight: FontWeight.bold),
                          ),
                          children: <Widget>[
                            Padding(
                              padding: const EdgeInsets.only(left: 20.0),
                              child: Column(
                                children: <Widget>[
                                  Row(
                                    children: <Widget>[
                                      Icon(
                                        Icons.location_on,
                                        color: primaryColor,
                                      ),
                                      Padding(
                                        padding: const EdgeInsets.all(8.0),
                                        child: Text('Pickup Address'),
                                      ),
                                    ],
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.only(left: 10.0),
                                    child: DeliveryAddressRow(
                                        shippingAddress: _shippingAddress),
                                  ),
                                  Container(
                                    padding: EdgeInsets.only(
                                        top: 20, bottom: 15, right: 15),
                                    child: Align(
                                      alignment: Alignment.bottomRight,
                                      child: Container(
                                        width: 120,
                                        height: 40,
                                        child: FloatingActionButton.extended(
                                          materialTapTargetSize:
                                              MaterialTapTargetSize.shrinkWrap,
                                          onPressed: () {},
                                          icon: Icon(Icons.add),
                                          label: Text(
                                            'Select\nAddress',
                                            style: TextStyle(fontSize: 12),
                                          ),
                                          backgroundColor: primaryColor,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              // child: ExpansionTile(
                              //   leading: Icon(
                              //     Icons.location_on,
                              //     color: primaryColor,
                              //   ),
                              //   title: Text('My Address'),
                              //   children: [
                              //     Padding(
                              //       padding: const EdgeInsets.only(left: 10.0),
                              //       child: ShippingAddressRow(
                              //           shippingAddress: _shippingAddress),
                              //     ),
                              //     Container(
                              //       padding: EdgeInsets.only(
                              //           top: 20, bottom: 15, right: 15),
                              //       child: Align(
                              //         alignment: Alignment.bottomRight,
                              //         child: Container(
                              //           width: 120,
                              //           height: 40,
                              //           child: FloatingActionButton.extended(
                              //             materialTapTargetSize:
                              //                 MaterialTapTargetSize.shrinkWrap,
                              //             onPressed: () {},
                              //             icon: Icon(Icons.add),
                              //             label: Text(
                              //               'Select\nAddress',
                              //               style: TextStyle(fontSize: 12),
                              //             ),
                              //             backgroundColor: primaryColor,
                              //           ),
                              //         ),
                              //       ),
                              //     ),
                              //   ],
                              // ),
                            ),
                            widget.pickUp == null
                                ? pickupTime
                                : widget.pickUp.status == 'Pending'
                                    ? pickupTime
                                    : pickupTimeReadOnly,
                            Padding(
                              padding: const EdgeInsets.only(left: 20.0),
                              child: Column(
                                children: <Widget>[
                                  SizedBox(height: 5),
                                  Container(height: 50.0, child: requestDateBox)
                                ],
                              ),
                            ),
                            SizedBox(height: 15.0),
                          ],
                        ),
                  // ExpansionTile(
                  //   title: Text(
                  //     'Package Information',
                  //     style: TextStyle(
                  //         color: primaryColor, fontWeight: FontWeight.bold),
                  //   ),
                  //   children: <Widget>[
                  //     Padding(
                  //       padding: const EdgeInsets.only(left: 20.0),
                  //       child: widget.pickUp == null
                  //           ? noOfPackageBox
                  //           : widget.pickUp.status == 'Pending'
                  //               ? noOfPackageBox
                  //               : noOfPackageBoxReadonly,
                  //     ),
                  //     Padding(
                  //       padding: const EdgeInsets.only(left: 20.0),
                  //       child: widget.pickUp == null
                  //           ? fcsInput("Total Weight (lb)",
                  //               FontAwesomeIcons.weightHanging,
                  //               controller: _weightEditingController)
                  //           : widget.pickUp.status == 'Pending'
                  //               ? fcsInput("Total Weight (lb)",
                  //                   FontAwesomeIcons.weightHanging,
                  //                   controller: _weightEditingController)
                  //               : fcsInputReadOnly("Total Weight (lb)",
                  //                   FontAwesomeIcons.weightHanging,
                  //                   controller: _weightEditingController),
                  //     ),
                  //     Padding(
                  //       padding: const EdgeInsets.only(left: 20.0),
                  //       child: fcsInput("Remark", MaterialCommunityIcons.note),
                  //     ),
                  //     Padding(
                  //       padding: const EdgeInsets.only(left: 3.0),
                  //       child: ExpansionTile(
                  //         leading: Icon(
                  //           SimpleLineIcons.location_pin,
                  //           color: primaryColor,
                  //         ),
                  //         title: Text(
                  //           'Shipping Address',
                  //         ),
                  //         children: [
                  //           ShippingAddressRow(
                  //               shippingAddress: _shippingAddress),
                  //           Container(
                  //             padding: EdgeInsets.only(
                  //                 top: 20, bottom: 15, right: 15),
                  //             child: Align(
                  //               alignment: Alignment.bottomRight,
                  //               child: Container(
                  //                 width: 130,
                  //                 height: 40,
                  //                 child: FloatingActionButton.extended(
                  //                   materialTapTargetSize:
                  //                       MaterialTapTargetSize.shrinkWrap,
                  //                   onPressed: () {},
                  //                   icon: Icon(Icons.add),
                  //                   label: Text(
                  //                     'Add Shipping\nAddress',
                  //                     style: TextStyle(fontSize: 12),
                  //                   ),
                  //                   backgroundColor: primaryColor,
                  //                 ),
                  //               ),
                  //             ),
                  //           ),
                  //         ],
                  //       ),
                  //     ),
                  //     SizedBox(height: 10.0),
                  //   ],
                  // ),
                  mainModel.isCustomer()
                      ? Container()
                      : ExpansionTile(
                          title: Text('For FCS'),
                          children: <Widget>[
                            widget.pickUp != null
                                ? widget.pickUp.status == 'Pending'
                                    ? Padding(
                                        padding:
                                            const EdgeInsets.only(left: 20.0),
                                        child: fcsDropDown("Assigned",
                                            MaterialCommunityIcons.worker),
                                      )
                                    : Container()
                                : Container(),
                            Padding(
                              padding: EdgeInsets.only(left: 20),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Container(
                                    padding: EdgeInsets.only(top: 8),
                                    child: Text(
                                      'Attach Courier Shiping Labels',
                                      style: TextStyle(
                                          color: Colors.black, fontSize: 16),
                                    ),
                                  ),
                                  Container(
                                      padding: EdgeInsets.only(left: 10),
                                      child: MultiImageFile(
                                        enabled: true,
                                        controller: multiImgController,
                                        title: "Receipt File",
                                      )),
                                ],
                              ),
                            ),
                          ],
                        ),
                ]),
              )),
              widget.pickUp == null
                  ? Align(
                      alignment: Alignment.bottomCenter,
                      child: Center(
                          child: Container(
                        width: 250,
                        child: FlatButton(
                          child: Text('Create shipment'),
                          color: primaryColor,
                          textColor: Colors.white,
                          onPressed: () {
                            Navigator.pop(context);
                          },
                        ),
                      )))
                  : Container(
                      child: Column(
                      children: <Widget>[
                        widget.pickUp.status == 'Confirmed'
                            ? Align(
                                alignment: Alignment.bottomCenter,
                                child: Center(
                                    child: Container(
                                  width: 250,
                                  child: FlatButton(
                                    child: Text('Complete Shipment'),
                                    color: primaryColor,
                                    textColor: Colors.white,
                                    onPressed: () {
                                      Navigator.pop(context);
                                    },
                                  ),
                                )))
                            : Align(
                                alignment: Alignment.bottomCenter,
                                child: Center(
                                    child: Container(
                                  width: 250,
                                  child: FlatButton(
                                    child: Text('Confirm Shipment'),
                                    color: primaryColor,
                                    textColor: Colors.white,
                                    onPressed: () {
                                      Navigator.pop(context);
                                    },
                                  ),
                                ))),
                        Align(
                            alignment: Alignment.bottomCenter,
                            child: Center(
                                child: Container(
                              width: 250,
                              child: FlatButton(
                                child: Text('Cancel Shipment'),
                                color: Colors.grey[600],
                                textColor: Colors.white,
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            )))
                      ],
                    ))
            ],
          ),
        ),
      ),
    );
  }

  List<Widget> getBoxList(BuildContext context, List<Box> boxes) {
    List<Box> _boxes = [boxes[0], boxes[1]];

    return _boxes.asMap().entries.map((_box) {
      DeliveryAddress shippingAddress = _box.value.shippingAddress;

      return InkWell(
        onTap: () {
          Navigator.of(context)
              .push(BottomUpPageRoute(PickupBoxEditor(box: _box.value)));
        },
        child: Container(
          padding: EdgeInsets.only(left: 10),
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Expanded(
                    child: new Padding(
                      padding: const EdgeInsets.symmetric(vertical: 10.0),
                      child: new Row(
                        children: <Widget>[
                          new Expanded(
                            child: new Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Padding(
                                  padding: const EdgeInsets.only(left: 8.0),
                                  child: new Text(
                                    shippingAddress.fullName == null
                                        ? ''
                                        : shippingAddress.fullName,
                                    style: new TextStyle(
                                        fontSize: 15.0,
                                        color: Colors.black,
                                        fontWeight: FontWeight.bold),
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(left: 8.0),
                                  child: new Text(
                                    shippingAddress.addressLine1 == null
                                        ? ''
                                        : shippingAddress.addressLine1,
                                    style: new TextStyle(
                                        fontSize: 14.0, color: Colors.grey),
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(left: 8.0),
                                  child: new Text(
                                    shippingAddress.addressLine2 == null
                                        ? ''
                                        : shippingAddress.addressLine2,
                                    style: new TextStyle(
                                        fontSize: 14.0, color: Colors.grey),
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(left: 8.0),
                                  child: new Text(
                                    shippingAddress.city == null
                                        ? ''
                                        : shippingAddress.city,
                                    style: new TextStyle(
                                        fontSize: 14.0, color: Colors.grey),
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(left: 8.0),
                                  child: new Text(
                                    shippingAddress.state == null
                                        ? ''
                                        : shippingAddress.state,
                                    style: new TextStyle(
                                        fontSize: 14.0, color: Colors.grey),
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(left: 8.0),
                                  child: new Text(
                                    shippingAddress.phoneNumber == null
                                        ? ''
                                        : "Phone:${shippingAddress.phoneNumber}",
                                    style: new TextStyle(
                                        fontSize: 14.0, color: Colors.grey),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(left: 8.0),
                        child: new Text(
                          "L${_box.value.length}xW${_box.value.weight}xH${_box.value.height}",
                          style: new TextStyle(
                              fontSize: 15.0, color: Colors.black),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 8.0),
                        child: new Text(
                          _box.value.weight == null
                              ? ''
                              : "Actual Weight:${_box.value.weight.toString()}lb",
                          style:
                              new TextStyle(fontSize: 14.0, color: Colors.grey),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 8.0),
                        child: new Text(
                          _box.value.shipmentWeight == null
                              ? ''
                              : "Shipment Weight:${_box.value.shipmentWeight.toString()}lb",
                          style:
                              new TextStyle(fontSize: 14.0, color: Colors.grey),
                        ),
                      ),
                    ],
                  )
                ],
              ),
              _box.key == _boxes.length - 1
                  ? Container()
                  : Divider(
                      color: Colors.black,
                    )
            ],
          ),
        ),
      );
    }).toList();
  }
}
