import 'package:fcs/domain/constants.dart';
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/entities/user.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/main/util.dart';
import 'package:fcs/pages/widgets/defalut_delivery_address.dart';
import 'package:fcs/pages/widgets/delivery_address_selection.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_vector_icons/flutter_vector_icons.dart';
import 'package:provider/provider.dart';

import 'cargo_type_addtion.dart';
import 'carton_cargo_table.dart';
import 'model/carton_model.dart';

class PackageCartonEditor extends StatefulWidget {
  final Carton? carton;
  final bool? isNew;
  final User? consignee;
  PackageCartonEditor({this.carton, this.isNew, this.consignee});

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

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

  Carton? _carton;
  bool _isLoading = false;
  DeliveryAddress? _deliveryAddress = new DeliveryAddress();
  List<CargoType> _cargoTypes = [];
  CartonSize? selectedCatonSize;
  bool isFromPackages = false;
  bool isFromCartons = false;

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

  _load() {
    _carton = widget.carton;
    isFromPackages = _carton!.cartonType == carton_from_packages;
    isFromCartons = _carton!.cartonType == carton_from_cartons;

    if (widget.isNew!) {
      _lengthCtl.text = "0";
      _widthCtl.text = "0";
      _heightCtl.text = "0";
    } else {
      _cargoTypes = widget.carton!.cargoTypes.map((e) => e.clone()).toList();
      _lengthCtl.text = _carton!.length.toString();
      _widthCtl.text = _carton!.width.toString();
      _heightCtl.text = _carton!.height.toString();
      _deliveryAddress = _carton!.deliveryAddress;
      _getCartonSize();
    }
  }

  _getCartonSize() {
    var cartonSizeModel = Provider.of<CartonSizeModel>(context, listen: false);
    cartonSizeModel.cartonSizes.forEach((c) {
      if (c.length == _carton!.length &&
          c.width == _carton!.width &&
          c.height == _carton!.height) {
        selectedCatonSize = CartonSize(
            id: c.id,
            name: c.name,
            length: c.length,
            width: c.width,
            height: c.height);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final lengthBox = LengthPicker(
      controller: _lengthCtl,
      lableKey: "box.length",
      isReadOnly: false,
    );
    final widthBox = LengthPicker(
      controller: _widthCtl,
      lableKey: "box.width",
      isReadOnly: false,
    );
    final heightBox = LengthPicker(
      controller: _heightCtl,
      lableKey: "box.height",
      isReadOnly: false,
    );
    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: widget.isNew! ? "box.new_carton_btn" : "box.cargo.save.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(() {
              _cargoTypes.addAll(
                  cargos.where((e) => !_cargoTypes.contains(e)).toList());
            });
          }),
    );

    final cargoTableBox = CargoTable(
      isNew: widget.isNew,
      cargoTypes: _cargoTypes,
      onRemove: (c) => _removeCargo(c),
      onUpdate: (c) => _updateCargo(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,
            widget.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,
              LocalTitle(textKey: "box.delivery_address"),
              DefaultDeliveryAddress(
                  deliveryAddress: _deliveryAddress,
                  labelKey: "box.delivery_address",
                  onTap: () async {
                    DeliveryAddress? d = await Navigator.push<DeliveryAddress>(
                      context,
                      CupertinoPageRoute(
                          builder: (context) => DeliveryAddressSelection(
                                deliveryAddress: _deliveryAddress,
                                user: User(
                                    id: _carton!.userID,
                                    name: _carton!.userName),
                              )),
                    );
                    if (d == null) return;
                    setState(() {
                      _deliveryAddress = d;
                    });
                  }),
              SizedBox(
                height: 20,
              ),
              createBtn
            ],
          ),
        ),
      ),
    );
  }

  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()),
    );
  }

  _removeCargo(CargoType cargo) {
    setState(() {
      _cargoTypes.remove(cargo);
    });
  }

  _updateCargo(CargoType cargo) {
    setState(() {
      var _c = _cargoTypes.firstWhere((e) => e.id == cargo.id);
      if (_c != null) {
        _c.weight = cargo.weight;
        _c.qty = cargo.qty;
      }
    });
  }

  _creatCarton() async {
    if (_cargoTypes.length == 0) {
      showMsgDialog(context, "Error", "Expect at least one cargo type");
      return;
    }
    double l = double.parse(_lengthCtl.text);
    double w = double.parse(_widthCtl.text);
    double h = double.parse(_heightCtl.text);
    if ((l <= 0 || w <= 0 || h <= 0)) {
      showMsgDialog(context, "Error", "Invalid dimension");
      return;
    }
    if (_deliveryAddress == null) {
      showMsgDialog(context, "Error", "Invalid delivery address");
      return;
    }

    Carton carton = Carton();
    carton.id = _carton!.id;
    carton.cartonType = _carton!.cartonType;
    carton.fcsShipmentID = _carton!.fcsShipmentID;
    carton.cargoTypes = _cargoTypes;
    if (isFromPackages) {
      carton.userID = _carton!.userID;
      carton.packages = _carton!.packages.where((e) => e.isChecked).toList();
    }

    if (isFromCartons) {
      carton.userID = _carton!.userID;
      carton.fcsID = _carton!.fcsID;
      carton.userName = _carton!.userName;
      carton.senderID = _carton!.senderID;
      carton.senderFCSID = _carton!.senderFCSID;
      carton.senderName = _carton!.senderName;
    }

    carton.length = l;
    carton.width = w;
    carton.height = h;
    carton.deliveryAddress = _deliveryAddress;
    setState(() {
      _isLoading = true;
    });
    try {
      CartonModel cartonModel =
          Provider.of<CartonModel>(context, listen: false);
      if (widget.isNew!) {
        Carton _c = await cartonModel.createCarton(carton);
        Navigator.pop(context, _c);
      } else {
        await cartonModel.updateCarton(carton);
        Carton _c = await cartonModel.getCarton(_carton!.id!);
        Navigator.pop(context, _c);
      }
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
