import 'package:fcs/domain/entities/cargo_type.dart';
import 'package:fcs/domain/entities/custom_duty.dart';
import 'package:fcs/domain/entities/discount_by_weight.dart';
import 'package:fcs/domain/entities/rate.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/localization/app_translations.dart';
import 'package:fcs/pages/rates/model/shipment_rate_model.dart';
import 'package:fcs/pages/widgets/input_text.dart';
import 'package:fcs/pages/widgets/my_data_table.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';

import '../main/util.dart';
import 'cargo_editor.dart';
import 'custom_editor.dart';

class ShipmentRatesEdit extends StatefulWidget {
  ShipmentRatesEdit();

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

class _ShipmentRatesEditState extends State<ShipmentRatesEdit> {
  bool _isLoading = false;
  TextEditingController _minWeight = new TextEditingController();
  TextEditingController _deliveryFee = new TextEditingController();
  TextEditingController _volumetricRatio = new TextEditingController();

  @override
  void initState() {
    super.initState();
    var shipmentRateModel =
        Provider.of<ShipmentRateModel>(context, listen: false);
    Rate rate = shipmentRateModel.rate;

    _minWeight.text = rate.freeDeliveryWeight?.toString() ?? "";
    _deliveryFee.text = rate.deliveryFee?.toString() ?? "";
    _volumetricRatio.text = rate.volumetricRatio?.toString() ?? "";
  }

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

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

    final minWigBox = InputText(
        labelTextKey: 'rate.min_weight',
        iconData: FontAwesomeIcons.weightHanging,
        controller: _minWeight);
    final feeBox = InputText(
        labelTextKey: 'rate.delivery_fee',
        iconData: Icons.attach_money,
        controller: _deliveryFee);
    final ratioBox = InputText(
        labelTextKey: 'rate.volumetric_ratio',
        iconData: Icons.attach_money,
        controller: _volumetricRatio);

    return LocalProgress(
      inAsyncCall: _isLoading,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          leading: new IconButton(
            icon: new Icon(
              CupertinoIcons.back,
            ),
            onPressed: () => Navigator.of(context).pop(),
          ),
          backgroundColor: primaryColor,
          title: Text(AppTranslations.of(context).text("rate.edit.title")),
        ),
        body: Container(
          padding: EdgeInsets.all(18),
          child: Column(
            children: <Widget>[
              Expanded(
                child: ListView(
                  children: <Widget>[
                    minWigBox,
                    feeBox,
                    ratioBox,
                    SizedBox(height: 10),
                  ],
                ),
              ),
              fcsButton(context, getLocalString(context, "btn.save"),
                  callack: _save),
              SizedBox(height: 10)
            ],
          ),
        ),
      ),
    );
  }

  _save() async {
    setState(() {
      _isLoading = true;
    });
    try {
      var shipmentRateModel =
          Provider.of<ShipmentRateModel>(context, listen: false);
      Rate _rate = new Rate(
          deliveryFee: double.parse(_deliveryFee.text),
          freeDeliveryWeight: double.parse(_minWeight.text),
          volumetricRatio: double.parse(_volumetricRatio.text));
      Rate r = new Rate();
      print('_rate =>$r');
      await shipmentRateModel.updateRate(_rate);
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  List<MyDataRow> getCargoRows(List<CargoType> cargos) {
    return cargos.map((r) {
      return MyDataRow(
        onSelectChanged: (selected) {
          Navigator.push(
            context,
            CupertinoPageRoute(builder: (context) => CargoEditor(cargo: r)),
          );
        },
        cells: [
          MyDataCell(
            new Text(
              r.name,
              style: textStyle,
            ),
          ),
          MyDataCell(
            new Text(
              r.rate.toString(),
              style: textStyle,
            ),
          ),
          MyDataCell(IconButton(icon: Icon(Icons.delete), onPressed: null)),
        ],
      );
    }).toList();
  }

  List<MyDataRow> getCustomsRows(List<CustomDuty> customs) {
    return customs.map((c) {
      return MyDataRow(
        onSelectChanged: (selected) {
          Navigator.push(
            context,
            CupertinoPageRoute(builder: (context) => CustomEditor(custom: c)),
          );
        },
        cells: [
          MyDataCell(
            new Text(
              c.productType,
              style: textStyle,
            ),
          ),
          MyDataCell(
            new Text(
              c.fee.toString(),
              style: textStyle,
            ),
          ),
          MyDataCell(IconButton(icon: Icon(Icons.delete), onPressed: null)),
        ],
      );
    }).toList();
  }

  List<MyDataRow> getDiscounts(List<DiscountByWeight> discounts) {
    return discounts.map((d) {
      return MyDataRow(
        onSelectChanged: (selected) {
          // Navigator.push(
          //   context,
          //  CupertinoPageRoute(builder: (context) => CargoEditor(rate: r)),
          // );
        },
        cells: [
          MyDataCell(
            new Text(
              "${d.weight} lb",
              style: textStyle,
            ),
          ),
          MyDataCell(
            Center(
              child: new Text(
                d.discount.toString(),
                style: textStyle,
              ),
            ),
          ),
          MyDataCell(IconButton(icon: Icon(Icons.delete), onPressed: null)),
        ],
      );
    }).toList();
  }

  _row(String desc, String price, String unit) {
    return Container(
        padding: EdgeInsets.only(left: 25, top: 5, bottom: 5),
        child: Row(
          children: <Widget>[
            Text('$desc ', style: TextStyle(fontSize: 15)),
            Spacer(),
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(bottom: 3.0),
                  child: Text(
                    '$price',
                    style: TextStyle(color: primaryColor, fontSize: 14),
                  ),
                ),
                Text(
                  '$unit',
                  style: TextStyle(color: Colors.grey, fontSize: 14),
                ),
              ],
            ),
            SizedBox(
              width: 50,
            ),
          ],
        ));
  }
}
