
import 'package:flutter/material.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';

import '../../constants.dart';
import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/user.dart';
import '../../routes.dart';
import '../../store/actions.dart';
import '../../store/store.dart';
import '../../utils/http_util.dart';
import '../../utils/util_web.dart' if (dart.library.io) '../../utils/util_io.dart';
import '../../utils/utils.dart';

class MobileUserProfile extends StatefulWidget {
  final Key? key;

  const MobileUserProfile({this.key})
      : super(key: key);

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

class MobileUserProfileState extends State<MobileUserProfile> {
  User _user;

  bool _showProgress;
  double _progress;

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

    return ListView(
      children: <Widget>[
        Container(
          padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 10.0, bottom: 10.0),
          child: Text(
            S.of(context).basic_info,
            style: TextStyle(
                fontSize: 12.0,
                color: Colors.grey
            ),
          ),
        ),
        Stack(
          children: <Widget>[
            Positioned(
              top: 0.0,
              left: 0.0,
              right: 0.0,
              bottom: -85.0,
              child: Visibility(
                visible: _showProgress,
                child: LinearPercentIndicator(
                  lineHeight: 10.0,
                  percent: _progress,
                  backgroundColor: Colors.transparent,
                  progressColor: Colors.blue,
                  linearStrokeCap: LinearStrokeCap.butt,
                ),
              ),
            ),
            Positioned(
              child: GestureDetector(
                child: Container(
                  padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 16.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        child: Text(
                          S.of(context).avatar,
                          style: TextStyle(

                          ),
                        ),
                      ),
                      Container(
                        child: Util.showImage('https:${_user.avatarUrl}',
                          width: 60,
                          height: 60,
                          fit: BoxFit.fill,
                          errorWidget: (context, url, error) => Icon(
                            Icons.account_circle,
                            size: 60.0,
                            color: Colors.grey,
                          ),
                        ),
                      ),
                    ],
                  ),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        color: Colors.black12,
                        width: 1.0,
                      ),
                    ),
                  ),
                ),
                onTap: () {
                  _getAvatar(context);
                },
              ),
            ),
          ],
        ),
        GestureDetector(
          child: Container(
            padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  child: Text(
                    S.of(context).nick_name,
                    style: TextStyle(

                    ),
                  ),
                ),
                Container(
                  child: Text(
                    _user.nickname,
                    style: TextStyle(
                        color: Colors.grey
                    ),
                  ),
                ),
              ],
            ),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Colors.black12,
                  width: 1.0,
                ),
              ),
            ),
          ),
          onTap: () {
            _changeNickname(context);
          },
        ),
        GestureDetector(
          child: Container(
            padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  child: Text(
                    S.of(context).my_addresses,
                    style: TextStyle(

                    ),
                  ),
                ),
                Container(
                  child: Icon(
                    Icons.arrow_forward_ios,
                    size: 14.0,
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Colors.black12,
                  width: 1.0,
                ),
              ),
            ),
          ),
          onTap: () {
            Routes.router.navigateTo(context, '/my-addresses/-1');
          },
        ),
        Container(
          padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 36.0, bottom: 10.0),
          child: Text(
            S.of(context).account_binding,
            style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
            ),
          ),
        ),
        GestureDetector(
          child: Container(
            padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 10.0, bottom: 16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        child: Icon(
                          Icons.phone_iphone,
                          size: 16.0,
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 5.0),
                        child: Text(
                          S.of(context).mobile_number,
                          style: TextStyle(

                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  child: Text(
                    _user.mobile != null && _user.mobile.isNotEmpty ? Utils.safePhoneNumber(_user.mobile) : S.of(context).not_binding,
                    style: TextStyle(
                      color: Colors.grey,
                    ),
                  ),
                ),
              ],
            ),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Colors.black12,
                  width: 1.0,
                ),
              ),
            ),
          ),
          onTap: () {
            Routes.router.navigateTo(context, '/change-mobile-email/1');
          },
        ),
        GestureDetector(
          child: Container(
            padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        child: Icon(
                          Icons.mail_outline,
                          size: 16.0,
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 5.0),
                        child: Text(
                          S.of(context).email,
                          style: TextStyle(

                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  child: Text(
                    _user.email != null && _user.email.isNotEmpty ? Utils.safePhoneNumber(_user.email) : S.of(context).not_binding,
                    style: TextStyle(
                      color: Colors.grey,
                    ),
                  ),
                ),
              ],
            ),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Colors.black12,
                  width: 1.0,
                ),
              ),
            ),
          ),
          onTap: () {
            Routes.router.navigateTo(context, '/change-mobile-email/0');
          },
        ),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    if (store.state.user == null) {
      Routes.router.navigateTo(context, '/login', replace: true);
    } else {
      print(store.state.user.toString());
      setState(() {
        _user = store.state.user;
        _showProgress = false;
        _progress = 0.0;
      });
    }
    eventBus.on<OnCurrentUserUpdated>().listen((event) {
      if (mounted) {
        setState(() {
          _user = store.state.user;
        });
      }
    });
    eventBus.on<OnProgressEvent>().listen((event) {
      if (mounted) {
        setState(() {
          _showProgress = event.showProgress;
          _progress = event.progress;
        });
      }
    });
  }

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

  void _getAvatar(BuildContext mainContext) {
    showDialog(
        context: mainContext,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return Util().getPicture(mainContext, _user);
        }
    );
  }

  void _updateCurrentUser() {
    store.dispatch(new UpdateCurrentUser(_user));
    eventBus.fire(new OnCurrentUserUpdated());
  }

  void _changeNickname(BuildContext context) {
    final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
    final nicknameController = TextEditingController();

    nicknameController.text = _user.nickname;

    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text(
              S.of(context).change_nickname,
            ),
            content: Container(
              child: Form(
                key: _formKey,
                child: TextFormField(
                  controller: nicknameController,
                  decoration: new InputDecoration(
                    enabledBorder: UnderlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.black12,
                      ),
                    ),
                    focusedBorder: UnderlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.blue,
                      ),
                    ),
                    labelText: S.of(context).enter_new_nickname,
                  ),
                  style: TextStyle(
                      fontSize: 18.0
                  ),
                  autofocus: true,
                  validator: (String? value) {
                    if (value.trim().isEmpty) {
                      return S.of(context).nickname_is_required;
                    }
                    return null;
                  },
                ),
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: Text(
                    S.of(context).cancel
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              TextButton(
                child: Text(
                  S.of(context).submit_to_change,
                ),
                onPressed: () {
                  final FormState form = _formKey.currentState;
                  if (form.validate()) {
                    Utils.getBox().then((box) {
                      int userId = box.get(Constants.KEY_USER_ID, defaultValue: 0);
                      HttpUtil.httpPut('v1/users/$userId', (response) {
                        Navigator.of(context).pop();
                        if (mounted) {
                          setState(() {
                            _user = User.fromJson(response.data);
                          });
                          _updateCurrentUser();
                        }
                      },
                        body: {
                          'nickname': nicknameController.text
                        },
                      );
                    }).catchError((error){
                      Navigator.of(context).pop();
                      Routes.router.navigateTo(context, '/login');
                    });
                  }
                },
              )
            ],
          );
        }
    );
  }
}