

import 'package:email_validator/email_validator.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_wisetronic/widgets/general/breadcrumbs.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../general/gender_selection.dart';

import '../../constants.dart';
import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/address.dart';
import '../../routes.dart';
import '../../store/actions.dart';
import '../../store/store.dart';
import '../../utils/http_util.dart';
import '../../utils/utils.dart';
import '../../widgets/general/navigationbar.dart';

class DesktopEditAddress extends StatefulWidget {
  final Key? key;
  final Address address;
  final int businessId;
  const DesktopEditAddress(this.address, {this.key, int businessId}) :
      businessId = businessId ?? Constants.BUSINESS_ID;

  @override
  State<StatefulWidget> createState() {
    return DesktopEditAddressState();
  }

}

class DesktopEditAddressState extends State<DesktopEditAddress> {
  final GlobalKey<FormState> _formKey = new GlobalKey();

  final contactNameController = TextEditingController();
  final phoneController = TextEditingController();
  final streetLine1Controller = TextEditingController();
  final streetLine2Controller = TextEditingController();
  final cityController = TextEditingController();
  final postalCodeController = TextEditingController();
  final emailController = TextEditingController();
  final faxController = TextEditingController();

  String country;
  Gender _selectedGender;

  String _selectedProvince;

  bool showLoading;

  double sideSpace = 0;
  double mainSpace = 1200;

  @override
  Widget build(BuildContext context) {
    store.dispatch(UpdateContext(context));

    if (MediaQuery.of(context).size.width <= 1200) {
      mainSpace = MediaQuery.of(context).size.width;
      sideSpace = 0;
    } else {
      mainSpace = 1200;
      sideSpace = (MediaQuery.of(context).size.width - 1200) / 2;
    }

    if (showLoading) {
      return new Scaffold(
        body: Center(
          child: SpinKitWave(
            color: Colors.lightBlueAccent,
            size: 40.0,
          ),
        ),
      );
    }

    Widget form = SingleChildScrollView(
      padding: EdgeInsets.only(
          left: 0.0, right: 0.0, top: 0.0, bottom: 0.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(
                left: 16.0, right: 16.0, top: 16.0, bottom: 0.0),
            child: TextFormField(
              controller: contactNameController,
              decoration: InputDecoration(
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.black12,
                  ),
                ),
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.blue,
                    )
                ),
                labelText: S
                    .of(context)
                    .contact_name,
              ),
              validator: (String? value) {
                if (value
                    .trim()
                    .isEmpty) {
                  return S
                      .of(context)
                      .contact_name_is_required;
                }
                return null;
              },
            ),
          ),
          GenderSelection(
            maleText: S
                .of(context)
                .mr,
            femaleText: S
                .of(context)
                .ms,
            selectedGenderIconBackgroundColor: Colors.indigo,
            checkIconAlignment: Alignment.bottomRight,
            selectedGenderCheckIcon: Icons.check,
            onChanged: (Gender gender) {
              _selectedGender = gender;
            },
            equallyAligned: true,
            animationDuration: Duration(milliseconds: 400),
            isCircular: true,
            isSelectedGenderIconCircular: true,
            opacityOfGradient: 0.6,
            padding: const EdgeInsets.all(3.0),
            size: 50,
            selectedGender: _selectedGender,
          ),
          Container(
            padding: EdgeInsets.only(
                left: 16.0, right: 16.0, top: 16.0, bottom: 0.0),
            child: TextFormField(
              keyboardType: TextInputType.phone,
              controller: phoneController,
              decoration: InputDecoration(
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.black12,
                  ),
                ),
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.blue,
                    )
                ),
                labelText: S
                    .of(context)
                    .mobile_phone_number,
              ),
              validator: (String? value) {
                if (value
                    .trim()
                    .isEmpty) {
                  return S
                      .of(context)
                      .mobile_phone_number_is_required;
                }
                return null;
              },
            ),
          ),
          Container(
            padding: EdgeInsets.only(
                left: 16.0, right: 16.0, top: 16.0, bottom: 0.0),
            child: TextFormField(
              controller: streetLine1Controller,
              decoration: InputDecoration(
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.black12,
                  ),
                ),
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.blue,
                    )
                ),
                labelText: S
                    .of(context)
                    .street_line_1,
              ),
              validator: (String? value) {
                if (value
                    .trim()
                    .isEmpty) {
                  return S
                      .of(context)
                      .street_line_1_is_required;
                }
                return null;
              },
            ),
          ),
          Container(
            padding: EdgeInsets.only(
                left: 16.0, right: 16.0, top: 16.0, bottom: 0.0),
            child: TextFormField(
              controller: streetLine2Controller,
              decoration: InputDecoration(
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.black12,
                  ),
                ),
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.blue,
                    )
                ),
                labelText: S
                    .of(context)
                    .street_line_2,
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.only(
                left: 16.0, right: 16.0, top: 16.0, bottom: 0.0),
            child: TextFormField(
              controller: cityController,
              decoration: InputDecoration(
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.black12,
                  ),
                ),
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.blue,
                    )
                ),
                labelText: S
                    .of(context)
                    .city,
              ),
              validator: (String? value) {
                if (value
                    .trim()
                    .isEmpty) {
                  return S
                      .of(context)
                      .city_is_required;
                }
                return null;
              },
            ),
          ),
          Container(
            padding: EdgeInsets.only(
                left: 16.0, right: 16.0, top: 16.0, bottom: 0.0),
            child: DropdownButton<String>(
              value: _selectedProvince,
              items: <String>[
                'Ontario',
                'Quebec',
                'British Columbia',
                'Alberta',
                'Manitoba',
                'Saskatchewan',
                'Nova Scotia',
                'New Brunswich',
                'Newfoundland and Labrador',
                'Prince Edward Island',
                'Northwest Territories',
                'Nunavut',
                'Yukon',
              ].map((value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
              onChanged: (newValue) {
                if (mounted) {
                  setState(() {
                    _selectedProvince = newValue;
                  });
                }
              },
              hint: Text(S
                  .of(context)
                  .province),
              isExpanded: true,
            ),
          ),
          Container(
            padding: EdgeInsets.only(
                left: 16.0, right: 16.0, top: 16.0, bottom: 0.0),
            child: TextFormField(
              controller: postalCodeController,
              decoration: InputDecoration(
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.black12,
                  ),
                ),
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.blue,
                    )
                ),
                labelText: S
                    .of(context)
                    .postal_code,
              ),
              validator: (String? value) {
                if (value
                    .trim()
                    .isEmpty) {
                  return S
                      .of(context)
                      .postal_code_is_required;
                }
                return null;
              },
            ),
          ),
          Container(
            padding: EdgeInsets.only(
                left: 16.0, right: 16.0, top: 32.0, bottom: 0.0),
            child: Text(
              S
                  .of(context)
                  .optional_information,
              style: TextStyle(
                fontSize: 12.0,
                color: Colors.grey,
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.only(
                left: 16.0, right: 16.0, top: 0.0, bottom: 0.0),
            child: TextFormField(
              controller: emailController,
              decoration: InputDecoration(
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.black12,
                  ),
                ),
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.blue,
                    )
                ),
                labelText: S
                    .of(context)
                    .email,
              ),
              validator: (String? value) {
                if (value.isNotEmpty && !EmailValidator.validate(value)) {
                  return S
                      .of(context)
                      .email_is_not_valid;
                }
                return null;
              },
            ),
          ),
          Container(
            padding: EdgeInsets.only(
                left: 16.0, right: 16.0, top: 16.0, bottom: 16.0),
            child: TextFormField(
              controller: faxController,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.black12,
                  ),
                ),
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.blue,
                    )
                ),
                labelText: S
                    .of(context)
                    .fax,
              ),
            ),
          ),
        ],
      ),
    );

    return Scaffold(
      appBar: MiniNavigationBar(
        title: S.of(context).edit_address,
        back: true,
        breadCrumbs: [
          BreadCrumb(S.of(context).edit_address, null),
        ],
        breadCrumbHeight: Constants.BREADCRUMB_HEIGHT,
      ),
      body: Form(
        key: _formKey,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: sideSpace,
            ),
            Container(
              width: mainSpace,
              child: form,
            ),
            Container(
              width: sideSpace,
            ),
          ],
        ),
      ),
      bottomNavigationBar: Container(
        padding: EdgeInsets.all(8.0),
        color: Theme
            .of(context)
            .buttonColor,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            TextButton(
              child: Text(
                S
                    .of(context)
                    .delete,
              ),
              onPressed: () {
                showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text(S
                            .of(context)
                            .warning),
                        content: Text(S
                            .of(context)
                            .are_you_sure_to_delete_the_address),
                        actions: <Widget>[
                          TextButton(
                            child: Text(S
                                .of(context)
                                .cancel),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                          ),
                          TextButton(
                            child: Text(S
                                .of(context)
                                .yes_i_am_sure),
                            onPressed: () {
                              Navigator.of(context).pop();
                              _deleteAddress();
                            },
                          )
                        ],
                      );
                    }
                );
              },
            ),
            TextButton(
              child: Text(
                  S
                      .of(context)
                      .save
              ),
              onPressed: () {
                _saveEditAddress();
              },
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      showLoading = false;
      _selectedProvince = widget.address.state;
      cityController.text = widget.address.city;
      postalCodeController.text = widget.address.zip;
      streetLine1Controller.text = widget.address.addressLine1;
      streetLine2Controller.text = widget.address.addressLine2;
      _selectedGender = widget.address.gender == 1 ? Gender.Male : Gender.Female;
      country = widget.address.country;
      contactNameController.text = widget.address.contactName;
      phoneController.text = widget.address.phone;
      emailController.text = widget.address.email;
      faxController.text = widget.address.fax;
    });
  }

  void _saveEditAddress() {
    final FormState form = _formKey.currentState;
    if (form.validate()) {
      if (mounted) {
        setState(() {
          showLoading = true;
        });
      }
      HttpUtil.httpPatch('v1/addresses/${widget.address.id}', (response) {
        if (mounted) {
          setState(() {
            showLoading = false;
          });
        }
        eventBus.fire(OnAddressesUpdated());
        if (widget.businessId > 0) {
          Routes.router.navigateTo(context, '/checkout/${widget.businessId}', replace: true);
        } else {
          Navigator.of(context).pop();
        }
      },
          body: {
            'id': widget.address.id,
            'name': contactNameController.text.trim(),
            'address_line1': streetLine1Controller.text.trim(),
            'address_line2': streetLine2Controller.text.trim(),
            'city': cityController.text.trim(),
            'state': _selectedProvince,
            'zip': postalCodeController.text.trim(),
            'phone': phoneController.text.trim(),
            'gender': _selectedGender == Gender.Male ? true : false,
            'email': emailController.text,
            'fax': faxController.text,
            'country': country,
          }
      ).catchError((error) {
        if (mounted) {
          setState(() {
            showLoading = false;
          });
        }
        Utils.showMessageDialog(context, error);
      });
    }
  }

  void _deleteAddress() {
    if (mounted) {
      setState(() {
        showLoading = true;
      });
    }
    HttpUtil.httpDelete('v1/addresses/${widget.address.id}', (response) {
      if (mounted) {
        setState(() {
          showLoading = false;
        });
      }
      Fluttertoast.showToast(
          msg: S.of(context).the_address_has_been_deleted,
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.black54,
          textColor: Colors.white
      );
      eventBus.fire(OnAddressesUpdated());
      Navigator.of(context).pop();
    }).catchError((error) {
      if (mounted) {
        setState(() {
          showLoading = false;
        });
      }
      Utils.showMessageDialog(context, error);
    });
  }
}