import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
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/pages/social/user_detail_page.dart';
import 'package:sport/pages/social/user_friend_add_page.dart';
import 'package:sport/provider/lib/provider_widget.dart';
import 'package:sport/provider/lib/view_state_lifecycle.dart';
import 'package:sport/provider/user_friend_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/utils/DateFormat.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 UserFriendPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PageState();
}

class _PageState extends State<UserFriendPage> {
  PageController _controller;
  bool _refresh = false;
  int _page =0;

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

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

  @override
  Widget build(BuildContext context) {
    final double tabHeader = 60;
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    final double pinnedHeaderHeight =
        //statusBar height
        statusBarHeight +
            //pinned SliverAppBar height in header
            kToolbarHeight +
            tabHeader;
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        backgroundColor: Colors.white,
        body: NestedScrollView(
          pinnedHeaderSliverHeightBuilder: () {
            return pinnedHeaderHeight;
          },
          innerScrollPositionKeyBuilder: () {
            TabController tabController = DefaultTabController.of(context);
            String index = 'Tab${tabController.index}';
            return Key(index);
          },
          headerSliverBuilder: (context, innerBoxIsScrolled) {
            return <Widget>[
              buildSliverAppBar(context, "好友列表", innerBoxIsScrolled: innerBoxIsScrolled, actions: <Widget>[
                IconButton(
                  icon: Text(
                    "添加",
                    style: TextStyle(fontSize: 15, color: Theme.of(context).accentColor),
                  ),
                  onPressed: () async {
                    await NavigatorUtil.goPage(context, (context) => UserFriendAddPage());
                    setState(() {
                      _refresh = true;
                    });
                    await Future.delayed(Duration(seconds: 1));
                    setState(() {
                      _refresh = false;
                    });
                  },
                )
              ]),
              SliverPersistentHeader(
                delegate: PersistentHeader(
                    min: tabHeader,
                    max: tabHeader,
                    child: Container(
                      color: Colors.white,
                      child: Column(
                        children: <Widget>[
                          Expanded(
                            child: Center(
                              child: Container(
                                height: 35,
                                child: TabBar(
                                  isScrollable: true,
                                  labelPadding: EdgeInsets.symmetric(horizontal: 32),
                                  indicatorWeight: 3,
                                  indicatorPadding: EdgeInsets.symmetric(horizontal: 6),
                                  tabs: <Widget>[Tab(text: '好友'), Tab(text: '我关注'), Tab(text: '关注我')],
                                  onTap: (index) {
                                    _controller?.jumpToPage(index);
                                  },
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    )),
                pinned: true,
              ),
            ];
          },
          body: _refresh? RequestLoadingWidget(): PageView.builder(
              controller: _controller = PageController(initialPage: _page)..addListener(() {
                _page = _controller.page.toInt();
              }),
              physics: NeverScrollableScrollPhysics(),
              itemCount: 3,
              itemBuilder: (_, index) => _PageDetailPage(index)),
        ),
      ),
    );
  }
}

class _PageDetailPage extends StatefulWidget {
  final int type;

  _PageDetailPage(this.type);

  @override
  State<StatefulWidget> createState() => _PageDetailState(type);
}

class _PageDetailState extends ViewStateLifecycle<_PageDetailPage, UserFriendModel>  {
  TextEditingController _controller;
  FocusNode _focusNode;
  ValueNotifier<String> _searchValue = ValueNotifier<String>("");

  _PageDetailState(int type);

  @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 ProviderWidget<UserFriendModel>(
        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>[
              SliverToBoxAdapter(
                child: _searchWidget(context),
              ),
              if (widget.type == 2)
                SliverToBoxAdapter(
                  child: Center(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Row(
                        children: <Widget>[
                          Image.asset("lib/assets/img/linkpop_icon_modify.png"),
                          SizedBox(
                            width: 6,
                          ),
                          Text(
                            "互相关注后可成为好友",
                            style: TextStyle(fontSize: 12, color: Color(0xffcecece)),
                          )
                        ],
                        mainAxisSize: MainAxisSize.min,
                      ),
                    ),
                  ),
                ),
              if (model.isBusy)
                SliverToBoxAdapter(
                  child: RequestLoadingWidget(),
                ),
              if (model.isEmpty)
                SliverToBoxAdapter(
                  child: RequestErrorWidget(
                    null,
                    msg: widget.type == 0 ? "暂无好友~" : widget.type == 1 ? "暂无关注~" : "暂无关注我的~",
                  ),
                ),
              if (model.isIdle)
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (context, index) {
                      return _buildItem(model.list[index]);
                    },
                    childCount: model.list.length,
                  ),
                ),
              if (model.isError)
                SliverToBoxAdapter(
                  child: RequestErrorWidget(
                    () {
                      model.initData();
                    },
                    msg: widget.type == 0 ? "暂无好友~" : widget.type == 1 ? "暂无关注~" : "暂无关注我的~",
                  ),
                ),
            ],
          );
        });
  }

  Widget _buildItem(UserFriend user) {
    var _padding = EdgeInsets.symmetric(horizontal: 4.0);
    Widget child;
    if (widget.type == 2) {
      child = Row(
        children: <Widget>[
          CircleAvatar(
            backgroundImage: userAvatarProvider(user?.socialInfo?.avatar),
            radius: 22,
          ),
          SizedBox(
            width: 8,
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  "${user?.socialInfo?.name}",
                  style: Theme.of(context).textTheme.headline3,
                ),
                SizedBox(
                  height: 5,
                ),
                Text(
                  "${DateFormat.formatCreateAt(user?.createdAt)}关注了你",
                  style: Theme.of(context).textTheme.bodyText1,
                ),
              ],
            ),
          ),
          if (user?.isFriends == "0")
            user?.isIgnore == 0
                ? GestureDetector(
                    child: Container(
                      width: 64,
                      height: 30,
                      alignment: Alignment.center,
                      margin: _padding,
                      child: Text(
                        "忽略",
                        strutStyle: fixedLine,
                        style: Theme.of(context).textTheme.bodyText2,
                      ),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(20),
                        border: Border.all(
                          color: Color(0xff999999),
                          width: .5,
                        ),
                      ),
                    ),
                    onTap: () async {
                      await request(context, () async {
                        var resp = await model.api.userIgnoreFollow(uid: user?.socialInfo?.id).catchError((onError) {});
                        if (resp?.code == 0) {
                          setState(() {
                            user.isIgnore = 1;
                          });
                        }
                      });
                    },
                  )
                : Container(
              width: 64,
              height: 30,
              margin: _padding,
              alignment: Alignment.center,
              child: Text(
                "已忽略",
                strutStyle: fixedLine,
                style: Theme.of(context).textTheme.bodyText2,
              ),
            ),
          if (user?.isIgnore == 0)
            user.isFriends == "1"
                ? Container(
                    width: 64,
                    height: 30,
                    margin: _padding,
                    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: _padding,
                      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.isFriends == "1") return;
                      await request(context, () async {
                        var resp = await model.api.userFollow(uid: user?.socialInfo?.id).catchError((onError) {});
                        if (resp?.code == 0) {
                          ToastUtil.show("关注成功");
                          setState(() {
                            user.isFriends = "1";
                          });
                        }
                      });
                    },
                  )
        ],
      );
    } else if (widget.type == 1) {
      child = Row(
        children: <Widget>[
          CircleAvatar(
            backgroundImage: userAvatarProvider(user?.socialInfo?.avatar),
            radius: 22,
          ),
          SizedBox(
            width: 8,
          ),
          Expanded(
            child: Text(
              "${user?.socialInfo?.name}",
              style: Theme.of(context).textTheme.headline3,
            ),
          ),
          GestureDetector(
            child: Container(
              width: 82,
              height: 30,
              alignment: Alignment.center,
              child: Text(
                "取消关注",
                strutStyle: fixedLine,
                style: Theme.of(context).textTheme.bodyText2,
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                  color: Color(0xff999999),
                  width: .5,
                ),
              ),
            ),
            onTap: () async {
              await request(context, () async {
                var resp = await model.api.userUnFollow(uid: user?.socialInfo?.id).catchError((onError) {});
                if (resp?.code == 0) {
                  ToastUtil.show("取关成功");
                  setState(() {
                    model.list?.remove(user);
                    if(model.list?.isEmpty == true){
                      model.initData();
                    }
                  });
                }
              });
            },
          )
        ],
      );
    } else {
      child = Row(
        children: <Widget>[
          CircleAvatar(
            backgroundImage: userAvatarProvider(user?.socialInfo?.avatar),
            radius: 22,
          ),
          SizedBox(
            width: 8,
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  "${user?.socialInfo?.name}",
                  style: Theme.of(context).textTheme.headline3,
                ),
                SizedBox(
                  height: 5,
                ),
                Text(
                  "${DateFormat.formatCreateAt(user?.updatedAt)}在线",
                  style: Theme.of(context).textTheme.bodyText1,
                ),
              ],
            ),
          ),
        ],
      );
    }
    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(12.0),
          child: InkWell(
              onTap: () async {
                await NavigatorUtil.goPage(
                    context,
                    (context) => UserDetailPage(PostUser(id: "${user?.socialInfo?.id}", name: user?.socialInfo?.name, avatar: user?.socialInfo?.avatar),
                        userFriends: model.list));
                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: (value) {
                _searchValue.value = value;
                setState(() {});
              },
              onSubmitted: (value) {
                model.submitValue(value);
                // _searchModel.setKeyword(value);
                // Provider.of<SearchModel>(context, listen: false).queryValue(value);
              },
            ),
          ),
          Visibility(
              visible: _searchValue.value?.isNotEmpty == true,
              child: GestureDetector(
                onTap: () {
                  model.submitValue(null);
                  _controller.clear();
                },
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Image.asset("lib/assets/img/searchbar_btn_no.png"),
                ),
              ))
        ],
      ),
    );
  }

  @override
  UserFriendModel createModel() => UserFriendModel(widget.type);

}
