import 'package:chat/data/UserData.dart';
import 'package:chat/models/friends_info.dart';
import 'package:flutter/material.dart';
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/conversation_table.dart';
import 'package:chat/utils/friend_list_mgr.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

class AddressSearchPage extends StatefulWidget {
  @override
  _AddressSearchPageState createState() => _AddressSearchPageState();
}

class _AddressSearchPageState extends State<AddressSearchPage> {
  ScrollController _scrollController;
  TextEditingController _txtCtrl = new TextEditingController();
  bool _hasdeleteIcon = false;

  List<FriendModel> searchList = [];

  List<FriendModel> friendList = [];

  FocusNode focusNode;
  //var _contactsFuture;
  @override
  void initState() {
    super.initState();
    focusNode = new FocusNode();
    _scrollController = new ScrollController();
    getFriendList();
  }

  getFriendList() async {
    friendList = await FriendListMgr().getFriendList();

    if (mounted) {
      setState(() {});
    }
  }

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

  @override
  Widget build(BuildContext context) {
    final List<Widget> _body = [];

    _body.add(ListView.builder(
      controller: _scrollController,
      itemBuilder: (BuildContext context, int index) {
        FriendModel _contact = searchList[index];

        return FriendsInfo(
            userId: _contact.friendId,
            avatar: _contact.avatar,
            title: Provider.of<RefNameProvider>(context)
                .getRefName(_contact.friendId, _contact.name),
            isShowDivder: true,
            groupTitle: null);
      },
      itemCount: searchList.length,
    ));

    return Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          backgroundColor: AppColors.NewAppbarBgColor,
          title: Text(I18n.of(context).search,
              textScaleFactor: 1.0, style: Constants.MainTitleStyle),
          centerTitle: true,
          leading: CustomUI.buildCustomLeading(context),
          elevation: 1,
          bottom: PreferredSize(
              preferredSize: Size.fromHeight(49),
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(bottom: 14, left: 12.5, right: 12.5),
                height: 35,
                decoration: BoxDecoration(
                    color: const Color(0xFFEEEEEE),
                    borderRadius: BorderRadius.all(Radius.circular(8))),
                child: TextField(
                    keyboardType: TextInputType.text,
                    textInputAction: TextInputAction.search,
                    controller: _txtCtrl,
                    focusNode: focusNode,
                    cursorColor: Constants.BlueTextColor,
                    maxLines: 1,
                    style: TextStyle(
                        textBaseline: TextBaseline.alphabetic, fontSize: 14.5),
                    autofocus: true,
                    inputFormatters: [
                      LengthLimitingTextInputFormatter(50),
                    ],
                    decoration: InputDecoration(
                      hintText: I18n.of(context).search,
                      hintStyle: TextStyle(fontSize: 14.5),
                      contentPadding: EdgeInsets.only(
                          left: 20,
                          top: (UserData().language == LanguageType.English ||
                                  UserData().language ==
                                      LanguageType.Vietnamese)
                              ? 3
                              : 10.5,
                          bottom: 10.5),
                      prefixIcon: Icon(
                        IconData(
                          0xe664,
                          fontFamily: Constants.IconFontFamily,
                        ),
                        color: const Color(0xFFA0A0A0),
                        size: 18,
                      ),
                      suffixIcon: Padding(
                          padding: EdgeInsetsDirectional.only(
                              start: 2.0, end: _hasdeleteIcon ? 20.0 : 0),
                          child: _hasdeleteIcon
                              ? new InkWell(
                                  onTap: (() {
                                    setState(() {
                                      WidgetsBinding.instance
                                          .addPostFrameCallback(
                                              (_) => _txtCtrl.clear());
                                      _hasdeleteIcon = false;
                                    });
                                  }),
                                  child: Icon(
                                    Icons.clear,
                                    size: 18.0,
                                    color: Constants.BlackTextColor,
                                  ))
                              : new Text('')),
                      filled: true,
                      fillColor: Colors.transparent,
                      border: InputBorder.none,
                    ),
                    onChanged: (str) async {
                      setState(() {
                        if (str.isEmpty) {
                          _hasdeleteIcon = false;
                        } else {
                          _hasdeleteIcon = true;
                          searchList = CustomUI().getSearchResult(
                              str, friendList == null ? [] : friendList);
                        }
                      });
                    },
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                    }),
              )),
        ),
        body: Stack(
          children: _body,
        ));
  }
}
