import 'package:flutter/material.dart' hide NestedScrollView;
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:sport/bean/post_user.dart';
import 'package:sport/bean/user_friend.dart';
import 'package:sport/bean/user_info.dart';
import 'package:sport/pages/social/user_detail_page.dart';
import 'package:sport/provider/lib/provider_widget.dart';
import 'package:sport/provider/lib/simple_model.dart';
import 'package:sport/provider/lib/view_state_lifecycle.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/utils/DateFormat.dart';
import 'package:sport/utils/click.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/dialog/request_dialog.dart';
import 'package:sport/widgets/error.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/loading.dart';
import 'package:sport/widgets/misc.dart';
import 'package:sport/widgets/persistent_header.dart';

class UserFriendAddPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PageState();
}

class _PageState extends ViewStateLifecycle<UserFriendAddPage, SimpleModel> with InjectApi {
  TextEditingController _controller;
  FocusNode _focusNode;
  ValueNotifier<String> _searchValue = ValueNotifier<String>("");

  @override
  SimpleModel createModel() => SimpleModel((page) async {
        if (_searchValue.value == "") return [];
        return (await api.userSearch(kw: _searchValue.value, page: page)).pageResult.results;
      });

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    _controller = new TextEditingController(text: '');
  }

  @override
  void dispose() {
    super.dispose();
    _focusNode?.dispose();
    _controller?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        leading: buildBackButton(context),
        title: Text(
          "添加好友",
          style: titleStyle,
        ),
      ),
      body: ProviderWidget<SimpleModel>(
          model: model,
          onModelReady: (model) => model.initData(),
          builder: (_, model, __) {
            return EasyRefresh.custom(
              firstRefresh: false,
              onRefresh: () => model.refresh(),
              onLoad: () => model.loadMore(),
              enableControlFinishRefresh: true,
              controller: model.refreshController,
              header: buildClassicalHeader(),
              footer: buildClassicalFooter(),
              slivers: <Widget>[
                SliverPersistentHeader(
                  delegate: PersistentHeader(
                      min: 50,
                      max: 50,
                      child: Container(
                        color: Colors.white,
                        child: _searchWidget(context),
                      )),
                  pinned: true,
                ),
                if (model.isBusy)
                  SliverToBoxAdapter(
                    child: RequestLoadingWidget(),
                  ),
                if (model.isEmpty || model.isError)
                  SliverToBoxAdapter(
                    child: RequestErrorWidget(
                      null,
                      msg: _searchValue.value == "" ? "请输入搜索的关键字" : "暂无相关用户~",
                    ),
                  ),
                if (model.isIdle)
                  SliverList(
                    delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        return _buildItem(model.list[index]);
                      },
                      childCount: model.list.length,
                    ),
                  ),
              ],
            );
          }),
    );
  }

  Widget _buildItem(UserInfo user) {
    Widget child = Row(
      children: <Widget>[
        CircleAvatar(
          backgroundImage: userAvatarProvider(user?.avatar),
          radius: 22,
        ),
        SizedBox(
          width: 8,
        ),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                "${user?.name}",
                style: Theme.of(context).textTheme.headline3,
              ),
              SizedBox(
                height: 4,
              ),
              Text(
                "ID: ${user?.id}",
                style: Theme.of(context).textTheme.bodyText2,
              ),
            ],
          ),
        ),
        user.isFriend()
            ? Container(
                width: 64,
                height: 30,
                margin: EdgeInsets.only(left: 8.0),
                alignment: Alignment.center,
                child: Text(
                  "已关注",
                  strutStyle: fixedLine,
                  style: Theme.of(context).textTheme.bodyText2.copyWith(color: Theme.of(context).accentColor),
                ),
              )
            : GestureDetector(
                child: Container(
                  width: 64,
                  height: 30,
                  margin: EdgeInsets.only(left: 8.0),
                  alignment: Alignment.center,
                  child: Text(
                    "关注",
                    strutStyle: fixedLine,
                    style: Theme.of(context).textTheme.bodyText2.copyWith(color: Theme.of(context).accentColor),
                  ),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    border: Border.all(
                      color: Theme.of(context).accentColor,
                      width: .5,
                    ),
                  ),
                ),
                onTap: () async {
                  if (user.isFriend()) return;
                  await request(context, () async {
                    var resp = await model.api.userFollow(uid: user?.id).catchError((onError) {});
                    if (resp?.code == 0) {
                      ToastUtil.show("关注成功");
                      setState(() {
                        user.followStatus = "followed";
                      });
                    }
                  });
                },
              )
      ],
    );
    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(12.0),
          child: InkWell(
              onTap: () async {
                List<UserFriend> friends = model.list.map((e) => UserFriend(uid: user.id, socialInfo: user, isFriends: user.isFriend() ? "1" : "0")).toList();
                await NavigatorUtil.goPage(
                    context, (context) => UserDetailPage(PostUser(id: "${user?.id}", name: user?.name, avatar: user?.avatar), userFriends: friends));
                user.followStatus = friends.firstWhere((element) => element.uid == user.id)?.isFriends == "1" ? "followed" : "none";
                setState(() {});
              },
              child: child),
        ),
        Divider(
          height: 1,
        )
      ],
    );
  }

  Widget _searchWidget(BuildContext context) {
    return Container(
      margin: EdgeInsets.fromLTRB(12.0, 6.0, 12.0, 6.0),
      height: 40,
      padding: EdgeInsets.fromLTRB(12.0, 0, 12.0, 0),
      decoration: BoxDecoration(
        color: Color(0xffF1F1F1),
        shape: BoxShape.rectangle,
        borderRadius: BorderRadius.all(Radius.circular(50)),
      ),
      child: Row(
        children: <Widget>[
          Image.asset("lib/assets/img/searchbar_icon_search.png"),
          SizedBox(
            width: 6,
          ),
          Expanded(
            child: TextField(
              controller: _controller,
              maxLines: 1,
              focusNode: _focusNode,
              decoration: InputDecoration(
                hintText: '输入账号/用户昵称',
                // contentPadding: EdgeInsets.all(10),
                border: InputBorder.none,
              ),
              onChanged: debounceValueChanged((value) {
                _searchValue.value = value;
                  model.initData();
              }),
              onSubmitted: (value) {
                _focusNode?.unfocus();
              },
            ),
          ),
          Visibility(
              visible: _searchValue.value?.isNotEmpty == true,
              child: GestureDetector(
                onTap: () {
                  _searchValue.value = "";
                  model.initData();
                  _controller.clear();
                },
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Image.asset("lib/assets/img/searchbar_btn_no.png"),
                ),
              ))
        ],
      ),
    );
  }
}
