import 'package:fcs/domain/vo/delivery_address.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/delivery_address/model/delivery_address_model.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/widgets/input_text.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class DeliveryAddressEditor extends StatefulWidget {
  final DeliveryAddress deliveryAddress;
  DeliveryAddressEditor({this.deliveryAddress});

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

class _DeliveryAddressEditorState extends State<DeliveryAddressEditor> {
  TextEditingController _nameController = new TextEditingController();
  TextEditingController _address1Controller = new TextEditingController();
  TextEditingController _address2Controller = new TextEditingController();
  TextEditingController _cityController = new TextEditingController();
  TextEditingController _stateController = new TextEditingController();
  TextEditingController _phoneController = new TextEditingController();

  DeliveryAddress _deliveryAddress = new DeliveryAddress();

  bool _isLoading = false;
  bool _isNew = true;

  @override
  void initState() {
    super.initState();
    if (widget.deliveryAddress != null) {
      _isNew = false;
      _deliveryAddress = widget.deliveryAddress;
      _nameController.text = _deliveryAddress.fullName;
      _address1Controller.text = _deliveryAddress.addressLine1;
      _address2Controller.text = _deliveryAddress.addressLine2;
      _cityController.text = _deliveryAddress.city;
      _stateController.text = _deliveryAddress.state;
      _phoneController.text = _deliveryAddress.phoneNumber;
    } else {
      _cityController.text = "Yangon";
      _stateController.text = "Yangon";
    }
  }

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

  @override
  Widget build(BuildContext context) {
    final fullName = InputText(
        labelTextKey: 'delivery_address.full_name',
        iconData: MaterialCommunityIcons.account_arrow_left,
        controller: _nameController);

    final addressLine1 = InputText(
        labelTextKey: 'delivery_address.address_line1',
        iconData: Icons.location_on,
        controller: _address1Controller);

    final addressLine2 = InputText(
        labelTextKey: 'delivery_address.address_line2',
        iconData: Icons.location_on,
        controller: _address2Controller);

    final cityBox = InputText(
        labelTextKey: 'delivery_address.city',
        iconData: Icons.location_city,
        controller: _cityController);

    final regionBox = InputText(
        labelTextKey: 'delivery_address.state_region',
        iconData: Entypo.location,
        controller: _stateController);

    final phoneNumberBox = InputText(
        labelTextKey: 'delivery_address.phonenumber',
        iconData: Icons.phone,
        textInputType: TextInputType.phone,
        controller: _phoneController);

    final createBtn = fcsButton(
      context,
      getLocalString(context, "delivery_address.create"),
      callack: _create,
    );

    final updateBtn = fcsButton(
      context,
      getLocalString(context, "delivery_address.update"),
      callack: _update,
    );

    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(),
            ),
            backgroundColor: Colors.white,
            shadowColor: Colors.transparent,
            title: LocalText(context, 'delivery_address',
                color: primaryColor, fontSize: 18),
            actions: [
              IconButton(
                  icon: Icon(
                    Icons.delete,
                    color: primaryColor,
                  ),
                  onPressed: _delete)
            ],
          ),
          body: Padding(
            padding: const EdgeInsets.only(left: 10.0, right: 10),
            child: ListView(children: <Widget>[
              fullName,
              SizedBox(height: 5),
              phoneNumberBox,
              SizedBox(height: 10),
              addressLine1,
              SizedBox(height: 5),
              addressLine2,
              SizedBox(height: 5),
              cityBox,
              SizedBox(height: 5),
              regionBox,
              SizedBox(height: 5),
              _isNew ? createBtn : updateBtn,
              SizedBox(height: 10)
            ]),
          ),
        ));
  }

  DeliveryAddress _getPayload() {
    DeliveryAddress deliveryAddress = DeliveryAddress();
    deliveryAddress.id = _deliveryAddress.id;

    try {
      deliveryAddress.fullName = _nameController.text;
      deliveryAddress.addressLine1 = _address1Controller.text;
      deliveryAddress.addressLine2 = _address2Controller.text;
      deliveryAddress.city = _cityController.text;
      deliveryAddress.state = _stateController.text;
      deliveryAddress.phoneNumber = _phoneController.text;
    } catch (e) {
      showMsgDialog(context, "Error", e.toString()); // shold never happen
    }
    return deliveryAddress;
  }

  Future<bool> _validate(DeliveryAddress deliveryAddress) async {
    if (deliveryAddress.addressLine1 == "") {
      await showMsgDialog(context, "Error", "Invalid address line 1!");
      return false;
    }

    if (deliveryAddress.city == null) {
      await showMsgDialog(context, "Error", "Invalid city!");
      return false;
    }
    if (deliveryAddress.state == null) {
      await showMsgDialog(context, "Error", "Invalid state!");
      return false;
    }
    if (deliveryAddress.phoneNumber == null) {
      await showMsgDialog(context, "Error", "Invalid phone number!");
      return false;
    }
    return true;
  }

  Future<void> _create() async {
    DeliveryAddress deliveryAddress = _getPayload();
    bool valid = await _validate(deliveryAddress);
    if (!valid) {
      return;
    }
    setState(() {
      _isLoading = true;
    });
    var deliveryAddressModel =
        Provider.of<DeliveryAddressModel>(context, listen: false);
    try {
      await deliveryAddressModel.createDeliveryAddress(deliveryAddress);
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _update() async {
    DeliveryAddress deliveryAddress = _getPayload();
    bool valid = await _validate(deliveryAddress);
    if (!valid) {
      return;
    }
    setState(() {
      _isLoading = true;
    });
    var deliveryAddressModel =
        Provider.of<DeliveryAddressModel>(context, listen: false);
    try {
      await deliveryAddressModel.updateDeliveryAddress(deliveryAddress);
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  _delete() {
    showConfirmDialog(context, "delivery_address.delete.confirm", _deleteDA);
  }

  _deleteDA() async {
    setState(() {
      _isLoading = true;
    });
    try {
      DeliveryAddressModel deliveryAddressModel =
          Provider.of<DeliveryAddressModel>(context, listen: false);
      await deliveryAddressModel.deleteDeliveryAddress(_deliveryAddress);
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
