import 'package:fcs/domain/entities/carton.dart';
import 'package:fcs/domain/entities/cargo_type.dart';
import 'package:fcs/domain/entities/carton_size.dart';
import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/domain/vo/delivery_address.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/carton_size/carton_size_list.dart';
import 'package:fcs/pages/carton_size/model/carton_size_model.dart';
import 'package:fcs/pages/delivery_address/model/delivery_address_model.dart';
import 'package:fcs/pages/rates/model/shipment_rate_model.dart';
import 'package:fcs/pages/widgets/defalut_delivery_address.dart';
import 'package:fcs/pages/widgets/delivery_address_selection.dart';
import 'package:fcs/pages/widgets/display_text.dart';
import 'package:fcs/pages/widgets/length_picker.dart';
import 'package:fcs/pages/widgets/local_button.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:provider/provider.dart';

import 'cargo_type_addtion.dart';
import 'carton_cargo_table.dart';

class PackageCartonEditor extends StatefulWidget {
  final Carton box;
  PackageCartonEditor({this.box});

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

class _PackageCartonEditorState extends State<PackageCartonEditor> {
  TextEditingController _lengthCtl = new TextEditingController();
  TextEditingController _widthCtl = new TextEditingController();
  TextEditingController _heightCtl = new TextEditingController();

  Carton _box;
  bool _isLoading = false;
  bool _isNew;
  double volumetricRatio = 0;
  double shipmentWeight = 0;

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

    volumetricRatio = Provider.of<ShipmentRateModel>(context, listen: false)
        .rate
        .volumetricRatio;

    if (widget.box != null) {
      _box = widget.box;
      _isNew = false;
      _lengthCtl.text = _box.length.toString();
      _widthCtl.text = _box.width.toString();
      _heightCtl.text = _box.height.toString();
    } else {
      var shipmentModel =
          Provider.of<DeliveryAddressModel>(context, listen: false);

      _isNew = true;
      _box = Carton(cargoTypes: []);
      _box.deliveryAddress = shipmentModel.defalutAddress;

      _lengthCtl.text = "12";
      _widthCtl.text = "12";
      _heightCtl.text = "12";
    }
    _lengthCtl.addListener(_calShipmentWeight);
    _widthCtl.addListener(_calShipmentWeight);
    _heightCtl.addListener(_calShipmentWeight);
    _calShipmentWeight();
  }

  _calShipmentWeight() {
    double l = double.parse(_lengthCtl.text, (s) => 0);
    double w = double.parse(_widthCtl.text, (s) => 0);
    double h = double.parse(_heightCtl.text, (s) => 0);
    setState(() {
      shipmentWeight = (l * w * h / volumetricRatio).ceilToDouble();
    });
  }

  @override
  Widget build(BuildContext context) {
    final shipmentWeightBox = DisplayText(
      labelTextKey: "box.shipment_weight",
      text: shipmentWeight == null ? "" : shipmentWeight.toStringAsFixed(0),
      iconData: MaterialCommunityIcons.weight,
    );

    final lengthBox = LengthPicker(
      controller: _lengthCtl,
      lableKey: "box.length",
      isReadOnly: true,
    );
    final widthBox = LengthPicker(
      controller: _widthCtl,
      lableKey: "box.width",
      isReadOnly: true,
    );
    final heightBox = LengthPicker(
      controller: _heightCtl,
      lableKey: "box.height",
      isReadOnly: true,
    );
    final dimBox = Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(right: 8.0),
          child: Icon(FontAwesome.arrow_circle_right, color: primaryColor),
        ),
        SizedBox(child: lengthBox, width: 80),
        SizedBox(child: widthBox, width: 80),
        SizedBox(child: heightBox, width: 80),
      ],
    );
    final createBtn = LocalButton(
      textKey: "box.new_carton_btn",
      callBack: _creatCarton,
    );

    final cargoTableTitleBox = LocalTitle(
      textKey: "box.cargo.type",
      trailing: IconButton(
          icon: Icon(
            Icons.add_circle,
            color: primaryColor,
          ),
          onPressed: () async {
            List<CargoType> cargos = await Navigator.push<List<CargoType>>(
                context,
                CupertinoPageRoute(builder: (context) => CargoTypeAddition()));
            if (cargos == null) return;
            setState(() {
              _box.cargoTypes.clear();
              _box.cargoTypes.addAll(cargos);
            });
          }),
    );

    final cargoTableBox = CargoTable(
      cargoTypes: _box.cargoTypes,
      onAdd: (c) => _addCargo(c),
      onRemove: (c) => _removeCargo(c),
    );

    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,
            _isNew ? "boxes.create.title" : "box.edit.title",
            fontSize: 20,
            color: primaryColor,
          ),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: [
              cargoTableTitleBox,
              cargoTableBox,
              LocalTitle(textKey: "box.dimension"),
              cartonSizeDropdown(),
              dimBox,
              shipmentWeightBox,
              LocalTitle(textKey: "box.delivery_address"),
              DefaultDeliveryAddress(
                  deliveryAddress: _box.deliveryAddress,
                  labelKey: "box.delivery_address",
                  onTap: () async {
                    DeliveryAddress d = await Navigator.push<DeliveryAddress>(
                      context,
                      CupertinoPageRoute(
                          builder: (context) => DeliveryAddressSelection(
                                deliveryAddress: _box.deliveryAddress,
                              )),
                    );
                    if (d == null) return;
                    setState(() {
                      _box.deliveryAddress = d;
                    });
                  }),
              SizedBox(
                height: 20,
              ),
              createBtn
            ],
          ),
        ),
      ),
    );
  }

  CartonSize selectedCatonSize;
  Widget cartonSizeDropdown() {
    List<CartonSize> _cartonSizes =
        Provider.of<CartonSizeModel>(context).getCartonSizes;

    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: Row(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 0, right: 10),
            child: Icon(AntDesign.CodeSandbox, color: primaryColor),
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.only(right: 18.0),
                  child: LocalText(
                    context,
                    "box.carton_size",
                    color: Colors.black54,
                    fontSize: 16,
                  ),
                ),
                DropdownButton<CartonSize>(
                  isDense: true,
                  value: selectedCatonSize,
                  style: TextStyle(color: Colors.black, fontSize: 14),
                  underline: Container(
                    height: 1,
                    color: Colors.grey,
                  ),
                  onChanged: (CartonSize newValue) {
                    setState(() {
                      if (newValue.name == MANAGE_CARTONSIZE) {
                        selectedCatonSize = null;
                        _manageCartonSize();
                        return;
                      }
                      selectedCatonSize = newValue;
                      _widthCtl.text = selectedCatonSize.width.toString();
                      _heightCtl.text = selectedCatonSize.height.toString();
                      _lengthCtl.text = selectedCatonSize.length.toString();
                    });
                  },
                  isExpanded: true,
                  items: _cartonSizes
                      .map<DropdownMenuItem<CartonSize>>((CartonSize value) {
                    return DropdownMenuItem<CartonSize>(
                      value: value,
                      child: Text(value.name ?? "",
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: value.name == MANAGE_CARTONSIZE
                                  ? secondaryColor
                                  : primaryColor)),
                    );
                  }).toList(),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _manageCartonSize() {
    Navigator.push<Package>(
      context,
      CupertinoPageRoute(builder: (context) => CartonSizeList()),
    );
  }

  _addCargo(CargoType cargo) {
    if (cargo == null) return;
    setState(() {
      _box.cargoTypes.remove(cargo);
      _box.cargoTypes.add(cargo);
    });
  }

  _removeCargo(CargoType cargo) {
    setState(() {
      _box.cargoTypes.remove(cargo);
    });
  }

  _creatCarton() {
    // double l = double.parse(_lengthCtl.text, (s) => 0);
    // double w = double.parse(_widthCtl.text, (s) => 0);
    // double h = double.parse(_heightCtl.text, (s) => 0);
    // _box.length = l;
    // _box.width = w;
    // _box.height = h;
    // Navigator.pop(context, _box);
  }
}
