import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/msgHandler.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

class AddFriendPage extends StatefulWidget {
  final int userId;
  final int pageType;
  final String originalName;
  AddFriendPage(
      {Key key,
      @required this.userId,
      @required this.pageType,
      @required this.originalName})
      : super(key: key);

  @override
  _AddFriendPageState createState() => new _AddFriendPageState();
}

class _AddFriendPageState extends State<AddFriendPage> {
  bool _hasdeleteIcon = false;
  TextEditingController _txtCtrl = new TextEditingController();

  @override
  void initState() {
    super.initState();

    print('AddFriendPage init111');
    _txtCtrl.text = widget.originalName;
    _hasdeleteIcon =
        !(widget.originalName == null || widget.originalName == "");
  }

  @override
  Widget build(BuildContext context) {
    String title = '';
    switch (widget.pageType) {
      case SendMessagePageType.AddFriends:
        title = I18n.of(context).friend_verification;
        break;
      case SendMessagePageType.ChangeGroupName:
        title = I18n.of(context).change_group_name;
        break;
      case SendMessagePageType.ChangeGroupNickName:
        title = I18n.of(context).my_group_nickname;
        break;
      case SendMessagePageType.Remark:
        title = I18n.of(context).setRemark;
        break;
      default:
    }
    Widget appBar = new AppBar(
      backgroundColor: AppColors.NewAppbarBgColor,
      title: new Text(
        title,
        textScaleFactor: 1.0,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
      ),
      centerTitle: true,
      leading: CustomUI.buildCustomLeading(context),
      actions: <Widget>[
        InkWell(
          onTap: () {
            var content = _txtCtrl.text;
            if (_txtCtrl.text.length == 0) {
              content = widget.originalName;
            }
            switch (widget.pageType) {
              case SendMessagePageType.AddFriends:
                HttpUtil().addFriends(context, widget.userId, content, () {
                  Navigator.of(context).pop();
                  MessageMgr().emit('post_add_friend', widget.userId);
                });
                break;
              case SendMessagePageType.ChangeGroupName:
                Navigator.of(context).pop();
                MsgHandler.updateGroupName(widget.userId, content);
                break;
              case SendMessagePageType.ChangeGroupNickName:
                Navigator.of(context).pop();
                MsgHandler.updateMemberRefName(widget.userId, content);
                break;
              case SendMessagePageType.Remark:
                Provider.of<RefNameProvider>(context)
                    .changeRefName(widget.userId, content, () {
                  Navigator.of(context).pop();
                });
                break;
              default:
            }
          },
          child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 15, bottom: 15, right: 20),
            height: 20,
            padding: EdgeInsets.only(left: 18, right: 18, bottom: 1),
            decoration: BoxDecoration(
                color: Constants.ConfrimButtonColor,
                borderRadius: BorderRadius.circular(4.5)),
            child: Text(
              widget.pageType == SendMessagePageType.AddFriends
                  ? I18n.of(context).send
                  : I18n.of(context).determine,
              style: TextStyle(color: Colors.white, fontSize: 14),
              textScaleFactor: 1.0,
            ),
          ),
        )
      ],
    );

    return Scaffold(appBar: appBar, body: SafeArea(child: _buildBody()));
  }

  Widget _buildBody() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _buildTips(),
          _buildInput(),
        ],
      ),
    );
  }

  Widget _buildInput() {
    return Container(
      height: 36.5,
      color: Colors.white,
      child: TextField(
        keyboardAppearance: Brightness.light,
        controller: _txtCtrl,
        //autofocus: true,
        style: TextStyle(
            fontSize: 16,
            color: Constants.BlackTextColor,
            textBaseline: TextBaseline.alphabetic),
        decoration: InputDecoration(
          contentPadding:
              EdgeInsets.only(right: 10, left: 15, top: 10, bottom: 10),
          hintText: widget.originalName,
          hintStyle: TextStyle(fontSize: 16, color: Colors.grey),
          border: InputBorder.none,
          suffixIcon: Padding(
              padding: EdgeInsetsDirectional.only(
                  start: 2.0, end: _hasdeleteIcon ? 20.0 : 0),
              child: _hasdeleteIcon
                  ? InkWell(
                      onTap: (() {
                        setState(() {
                          WidgetsBinding.instance
                              .addPostFrameCallback((_) => _txtCtrl.clear());
                          _hasdeleteIcon = false;
                        });
                      }),
                      child: Icon(
                        Icons.cancel,
                        size: 18.0,
                        color: const Color(0xFFDBDBDB),
                      ))
                  : Text('')),
        ),
        maxLines: 1,
        inputFormatters: [LengthLimitingTextInputFormatter(15)],
        onChanged: (str) async {
          setState(() {
            if (str.isEmpty) {
              _hasdeleteIcon = false;
            } else {
              _hasdeleteIcon = true;
            }
          });
        },
      ),
    );
  }

  Widget _buildTips() {
    String title = '';
    switch (widget.pageType) {
      case SendMessagePageType.AddFriends:
        title = I18n.of(context).added_friends_tips;
        break;
      case SendMessagePageType.ChangeGroupName:
        title = I18n.of(context).change_group_name;
        break;
      case SendMessagePageType.ChangeGroupNickName:
        title = I18n.of(context).my_group_nickname_tips;
        break;
      default:
    }
    return Container(
      margin: EdgeInsets.only(top: 20.5, left: 15, bottom: 6),
      child: Text(
        title,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 11),
      ),
    );
  }

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