import 'package:fcs/domain/entities/payment_method.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/main/model/main_model.dart';
import 'package:fcs/pages/payment_methods/model/payment_method_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/material.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:provider/provider.dart';

class PaymentMethodEditor extends StatefulWidget {
  final PaymentMethod paymentMethod;

  const PaymentMethodEditor({Key key, this.paymentMethod}) : super(key: key);
  @override
  _PaymentMethodEditorState createState() => _PaymentMethodEditorState();
}

class _PaymentMethodEditorState extends State<PaymentMethodEditor> {
  bool _isLoading = false;
  PaymentMethod _paymentMethod;
  TextEditingController _nameController = new TextEditingController();
  TextEditingController _accountNameController = new TextEditingController();
  TextEditingController _accountNumberController = new TextEditingController();
  TextEditingController _mailController = new TextEditingController();
  TextEditingController _phoneController = new TextEditingController();
  TextEditingController _linkController = new TextEditingController();

  bool isNew;

  @override
  void initState() {
    super.initState();
    isNew = widget.paymentMethod == null;

    if (widget.paymentMethod != null) {
      _paymentMethod = widget.paymentMethod;
      _nameController.text = _paymentMethod.name;
      _accountNameController.text = _paymentMethod.accountName;
      _accountNumberController.text = _paymentMethod.account;
      _mailController.text = _paymentMethod.email;
      _phoneController.text = _paymentMethod.phone;
      _linkController.text = _paymentMethod.link;
    } else {
      _paymentMethod = new PaymentMethod();
      _nameController.text = '';
    }
  }

  @override
  Widget build(BuildContext context) {
    return LocalProgress(
      inAsyncCall: _isLoading,
      child: Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            centerTitle: true,
            leading: new IconButton(
              icon: new Icon(CupertinoIcons.back, color: primaryColor),
              onPressed: () => Navigator.of(context).pop(),
            ),
            title: LocalText(
              context,
              isNew ? "pm.form.new" : "pm.update",
              fontSize: 20,
              color: primaryColor,
            ),
            shadowColor: Colors.transparent,
            backgroundColor: Colors.white,
            actions: <Widget>[
              isNew
                  ? Container()
                  : IconButton(
                      icon: Icon(
                        Icons.delete,
                        color: primaryColor,
                      ),
                      onPressed: _delete,
                    )
            ],
          ),
          body: Padding(
            padding: const EdgeInsets.only(left: 20.0, right: 10),
            child: ListView(
              children: <Widget>[
                InputText(
                  labelTextKey: "pm.name",
                  iconData: Octicons.tag,
                  controller: _nameController,
                ),
                InputText(
                  labelTextKey: "pm.account.name",
                  iconData: MaterialCommunityIcons.bank,
                  controller: _accountNameController,
                ),
                InputText(
                  labelTextKey: "pm.account.no",
                  iconData: MaterialCommunityIcons.checkbook,
                  controller: _accountNumberController,
                ),
                InputText(
                  labelTextKey: "pm.phone",
                  iconData: Icons.phone,
                  controller: _phoneController,
                ),
                InputText(
                  labelTextKey: "pm.email",
                  iconData: Icons.mail,
                  controller: _mailController,
                ),
                InputText(
                  labelTextKey: "pm.link",
                  iconData: Icons.link,
                  controller: _linkController,
                ),
                SizedBox(
                  height: 20,
                ),
                isNew
                    ? fcsButton(context, getLocalString(context, "pm.add.btn"),
                        callack: _add)
                    : fcsButton(context, getLocalString(context, "pm.save.btn"),
                        callack: _save),
                SizedBox(
                  height: 30,
                )
              ],
            ),
          )),
    );
  }

  _add() async {
    if (_nameController.text == "") {
      showMsgDialog(context, "Error", "Need a name for a payment method");
      return;
    }
    setState(() {
      _isLoading = true;
    });
    try {
      PaymentMethod pm = PaymentMethod(
          name: _nameController.text,
          accountName: _accountNameController.text,
          account: _accountNumberController.text,
          email: _mailController.text,
          phone: _phoneController.text,
          link: _linkController.text);
      await Provider.of<PaymentMethodModel>(context, listen: false)
          .addPaymentMethod(pm);
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  _save() async {
    if (_nameController.text == "") {
      showMsgDialog(context, "Error", "Need a name for a payment method");
      return;
    }
    setState(() {
      _isLoading = true;
    });
    try {
      PaymentMethod pm = PaymentMethod(
          id: _paymentMethod.id,
          name: _nameController.text,
          accountName: _accountNameController.text,
          account: _accountNumberController.text,
          email: _mailController.text,
          phone: _phoneController.text,
          link: _linkController.text);
      await Provider.of<PaymentMethodModel>(context, listen: false)
          .updatePaymentMethod(pm);
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  _delete() {
    showConfirmDialog(context, "pm.delete.confirm", () => _deleteConfirmed());
  }

  _deleteConfirmed() async {
    setState(() {
      _isLoading = true;
    });
    try {
      await Provider.of<PaymentMethodModel>(context, listen: false)
          .deletePaymentMethod(_paymentMethod.id);
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
