import 'package:fcs/domain/constants.dart';
import 'package:fcs/domain/entities/shipment.dart';
import 'package:fcs/domain/entities/user.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/shipment/model/shipment_model.dart';
import 'package:fcs/pages/staff/model/staff_model.dart';
import 'package:fcs/pages/widgets/input_text.dart';
import 'package:fcs/pages/widgets/local_button.dart';
import 'package:fcs/pages/widgets/local_dropdown.dart';
import 'package:fcs/pages/widgets/local_radio_buttons.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:fcs/pages/widgets/local_title.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import 'widgets.dart';

class ShipmentAssign extends StatefulWidget {
  final Shipment shipment;
  ShipmentAssign({this.shipment});

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

class _ShipmentAssignState extends State<ShipmentAssign> {
  var dateFormatter = new DateFormat('dd MMM yyyy');
  var timeFormatter = new DateFormat('jm');

  TextEditingController _fromTimeEditingController =
      new TextEditingController();
  TextEditingController _toTimeEditingController = new TextEditingController();
  TextEditingController _pickupDate = new TextEditingController();
  TextEditingController _handlingFee = new TextEditingController();

  Shipment _shipment;
  bool _isLoading = false;
  var now = new DateTime.now();

  String _selectedShipmentType;
  User _user;
  List<User> _users;

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

    _shipment = widget.shipment;
    _loadUsers();

    _selectedShipmentType = _shipment.shipmentType;
    _fromTimeEditingController.text = _shipment.pickupTimeStart;
    _toTimeEditingController.text = _shipment.pickupTimeEnd;
    _pickupDate.text = dateFormatter.format(_shipment.pickupDate ?? now);
    _handlingFee.text = _shipment.handlingFee?.toString() ?? "0";
  }

  _loadUsers() async {
    StaffModel staffModel = Provider.of<StaffModel>(context, listen: false);
    var users = await staffModel.getPickupEmployees();
    var selectUser = users.firstWhere((e) => e.id == _shipment.pickupUserID,
        orElse: () => null);
    setState(() {
      _users = users;
      _user = selectUser;
    });
  }

  @override
  Widget build(BuildContext context) {
    ShipmentModel pickupModel = Provider.of<ShipmentModel>(context);
    final shipmentNumberBox = getShipmentNumberStatus(context, _shipment);
    bool isLocalPickup = _selectedShipmentType == shipment_local_pickup;
    bool isCourierPickup = _selectedShipmentType == shipment_courier_pickup;
    bool isLocalDropoff = _selectedShipmentType == shipment_local_dropoff;
    bool isCourierDropoff = _selectedShipmentType == shipment_courier_dropoff;

    var usersBox = LocalDropdown<User>(
      callback: (v) {
        setState(() {
          _user = v;
        });
      },
      labelKey: "shipment.staff",
      iconData: MaterialCommunityIcons.worker,
      display: (u) => u.name,
      selectedValue: _user,
      values: _users,
    );

    final assignBtn = LocalButton(
      textKey: "shipment.assign.btn",
      callBack: _save,
    );
    final handlingFeeBox = InputText(
      labelTextKey: "shipment.handling.fee",
      controller: _handlingFee,
      iconData: FontAwesome.truck,
    );
    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(),
          ),
          shadowColor: Colors.transparent,
          backgroundColor: Colors.white,
          title: LocalText(
            context,
            "shipment.assign.title",
            fontSize: 20,
            color: primaryColor,
          ),
        ),
        body: Padding(
          padding: const EdgeInsets.all(10.0),
          child: ListView(
            children: <Widget>[
              Center(child: shipmentNumberBox),
              SizedBox(
                height: 10,
              ),
              LocalTitle(textKey: "shipment.assign.for.pickup"),
              usersBox,
              handlingFeeBox,
              SizedBox(
                height: 10,
              ),
              assignBtn,
            ],
          ),
        ),
      ),
    );
  }

  _save() async {
    _shipment.pickupUserID = this._user.id;
    _shipment.handlingFee = double.tryParse(_handlingFee.text) ?? 0;
    setState(() {
      _isLoading = true;
    });
    try {
      ShipmentModel shipmentModel =
          Provider.of<ShipmentModel>(context, listen: false);
      await shipmentModel.assignShipment(_shipment);
      Navigator.pop(context, true);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
