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

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

class DesktopNewAddress extends StatefulWidget {
  final Key key;
  final LocatedAddress locatedAddress;
  final int businessId;
  const DesktopNewAddress({this.key, this.locatedAddress, this.businessId}) : super(key: key);

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

}

class DesktopNewAddressState extends State<DesktopNewAddress> {
  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 = 'CA';
  Gender _selectedGender;

  String _selectedProvince;

  double sideSpace = 0;
  double mainSpace = 1200;

  List<String> provinces = <String>[
    'Ontario',
    'Quebec',
    'British Columbia',
    'Alberta',
    'Manitoba',
    'Saskatchewan',
    'Nova Scotia',
    'New Brunswich',
    'Newfoundland and Labrador',
    'Prince Edward Island',
    'Northwest Territories',
    'Nunavut',
    'Yukon',
  ];

  @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;
    }

    Widget form = SingleChildScrollView(
      padding: EdgeInsets.only(left: 0.0, right: 0.0, top: 0.0, bottom: 0.0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.start,
        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: provinces.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).new_address,
        back: true,
        breadCrumbs: [
          BreadCrumb(S.of(context).new_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>[
            SizedBox(),
            FlatButton(
              child: Text(
                  S.of(context).save
              ),
              onPressed: () {
                _saveNewAddress();
              },
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      if (widget.locatedAddress != null) {
        if (provinces.contains(widget.locatedAddress.province)) {
          _selectedProvince = widget.locatedAddress.province;
        }
        cityController.text = widget.locatedAddress.city;
        postalCodeController.text = widget.locatedAddress.postalCode;
        streetLine1Controller.text = (widget.locatedAddress.streetNumber != null
            && widget.locatedAddress.streetNumber.isNotEmpty
            ? widget.locatedAddress.streetNumber + ' ' : '')
            + widget.locatedAddress.streetName;
      } else {
        _selectedProvince = 'Ontario';
      }
      streetLine2Controller.text = '';
      _selectedGender = Gender.Male;
    });
  }

  void _saveNewAddress() {
    final FormState form = _formKey.currentState;
    if (form.validate()) {

      HttpUtil.httpPost('v1/addresses', (response) {
        if (widget.businessId > 0) {
          Routes.router.navigateTo(context, '/checkout/${widget.businessId}', replace: true);
        } else {
          Routes.router.navigateTo(context, '/my-addresses/${widget.businessId}', replace: true);
        }
      },
          body: {
            '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 ? 1 : 0,
            'email': emailController.text,
            'fax': faxController.text,
            'country': country,
          }
      );
    }
  }
}