import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:provider/provider.dart';
import 'package:sport/bean/post.dart';
import 'package:sport/pages/social/post_widget.dart';
import 'package:sport/provider/lib/provider_widget.dart' as p;
import 'package:sport/provider/lib/provider_widget_selector.dart';
import 'package:sport/provider/search_model.dart';
import 'package:sport/provider/social_detail_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/services/api/resp.dart';
import 'package:sport/services/userid.dart';
import 'package:sport/widgets/appbar.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/space.dart';

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

class _PageState extends State<SearchPage> with UserId {
  TextEditingController _controller;
  FocusNode _focusNode;

  SearchModel _model;
  SocialDetailModel _searchModel;

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    _controller = new TextEditingController(text: '');
    _model = SearchModel()
      ..getHistory()
      ..getHot();
    _searchModel = SocialDetailModel("0", 100);
  }

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

  _submitValue(String value) {
    _controller.text = value;
    _searchModel.setKeyword(value);
    _model.queryValue(value);
    _focusNode?.unfocus();
  }

  @override
  Widget build(BuildContext context) {
    return ProviderWidget<SearchModel, SearchBody>(
      model: _model,
      selector: (_, model) {
        return model.currentBody;
      },
      shouldRebuild: (_, __) => true,
      builder: (BuildContext context, _body, Widget child) {
        Widget body;
        switch (_body) {
          case SearchBody.defaultBody:
            body = _buildDefaultWidget();
            break;
          case SearchBody.suggestions:
            body = buildSuggestions(context);
            break;
          case SearchBody.results:
            body = buildResults(context);
            break;
        }

        return Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            titleSpacing: 0,
            centerTitle: false,
            automaticallyImplyLeading: false,
            title: Container(
              margin: EdgeInsets.fromLTRB(12.0, 0, 6.0, 0),
              height: 35,
              decoration: BoxDecoration(
                color: Color(0xffF1F1F1),
                shape: BoxShape.rectangle,
                borderRadius: BorderRadius.all(Radius.circular(50)),
              ),
              child: Row(
                children: <Widget>[
                  Space(
                    width: 12,
                  ),
                  Image.asset("lib/assets/img/searchbar_icon_search.png"),

                  Expanded(
                      child: Selector<SearchModel, String>(
                    selector: (_, model) => model.searchValue,
                    builder: (context, _value, child) => TextField(
                      controller: _controller,
                      maxLines: 1,
                      focusNode: _focusNode,
                      decoration: InputDecoration(
                        hintText: '请输入搜索内容',
                          contentPadding: EdgeInsets.symmetric(vertical: 11.0, horizontal: 16.0),
                        border: InputBorder.none,
                        hintStyle: TextStyle(color: Color(0xff999999))
                      ),
                      onChanged: (value) {
                        Provider.of<SearchModel>(context, listen: false).updateSearchValue(value);
                      },
                      onSubmitted: (value) {
                        _submitValue(value);
                        // _searchModel.setKeyword(value);
                        // Provider.of<SearchModel>(context, listen: false).queryValue(value);
                      },
                    ),
                  )),
                  Visibility(
                      visible: context.select<SearchModel, String>((value) => value.searchValue).isNotEmpty,
                      child: GestureDetector(
                        onTap: () {
                          Provider.of<SearchModel>(context, listen: false).updateSearchValue("");
                          _controller.clear();
                        },
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Image.asset("lib/assets/img/searchbar_btn_no.png"),
                        ),
                      ))
                ],
              ),
            ),
            actions: <Widget>[
              buildActionButton("取消", () {
                Navigator.of(context).pop();
              }),
            ],
          ),
          body: AnimatedSwitcher(
            duration: const Duration(milliseconds: 300),
            child: body,
          ),
        );
      },
    );
  }

  Widget _buildDefaultWidget() {
    return CustomScrollView(
      slivers: <Widget>[
        SliverPadding(
          padding: EdgeInsets.all(12.0),
          sliver: SliverToBoxAdapter(
            child: Selector<SearchModel, List>(
              selector: (_, model) => model.hot,
              builder: (context, _value, child) {
                if (_value.isNotEmpty) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text("热门帖子", style: Theme.of(context).textTheme.headline3.copyWith(fontSize: 18)),
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 6.0),
                        child: Wrap(
                            spacing: 12,
                            children: _value.take(10).map((e) {
                              return GestureDetector(
                                  onTap: () {
                                    _controller.text = e;
                                    _submitValue(e);
                                    // _model.queryValue(e);
                                  },
                                  child: Chip(
                                    labelPadding: const EdgeInsets.fromLTRB(16.0, 0, 16.0, 0),
                                    label: Text("$e"),
                                    labelStyle: TextStyle(color: Color(0xff666666)),
                                    backgroundColor: Colors.white,
                                    shape: StadiumBorder(
                                      side: BorderSide(color: Color(0xffDCDCDC), width: 0.5),
                                    ),
                                  ));
                            }).toList()),
                      ),
                    ],
                  );
                }
                return Container();
              },
            ),
          ),
        ),
        SliverPadding(
          padding: EdgeInsets.all(12.0),
          sliver: SliverToBoxAdapter(
            child: Selector<SearchModel, List>(
              selector: (_, model) => model.history,
              builder: (context, _value, child) {
                if (_value != null && _value.isNotEmpty) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text("历史搜索", style: Theme.of(context).textTheme.headline3.copyWith(fontSize: 18)),
                          InkWell(
                            onTap: () {
                              _model.clearHistory();
                            },
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Image.asset("lib/assets/img/list_icon_del.png"),
                            ),
                          )
                        ],
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 6.0),
                        child: Wrap(
                          alignment: WrapAlignment.spaceBetween,
                          spacing: 12,
                          children: _value.map((e) {
                            return GestureDetector(
                                onTap: () {
                                  _controller.text = e;
                                  _submitValue(e);
                                  // _model.queryValue(e);
                                },
                                child: Chip(
                                  labelPadding: const EdgeInsets.fromLTRB(16.0, 0, 16.0, 0),
                                  label: Text("$e"),
                                  labelStyle: TextStyle(color: Color(0xff666666)),
                                  backgroundColor: Colors.white,
                                  shape: StadiumBorder(
                                    side: BorderSide(color: Color(0xffDCDCDC), width: 0.5),
                                  ),
                                ));
                          }).toList(),
                        ),
                      ),
                    ],
                  );
                }
                return Container();
              },
            ),
          ),
        )
      ],
    );
  }

  Widget buildSuggestions(BuildContext context) {
    return FutureBuilder(
      future: _model.api.getPostList(kw: _model.searchValue),
      builder: (context, AsyncSnapshot<RespPage<Post>> snapshot) => snapshot.connectionState == ConnectionState.done
          ? snapshot.data.code == 0
              ? snapshot.data.pageResult.results.isEmpty
                  ? Center(
                      child: RequestErrorWidget(
                      null,
                      msg: "暂时找不到您想搜索的东西喔",
                    ))
                  : ListView.separated(
                      itemBuilder: (context, index) {
                        var item = snapshot.data.pageResult.results[index];
                        return ListTile(
                          title: Text(
                            item.content,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          onTap: () {
//            query = '老孟 $index';
                            String value = item.content;
                            _submitValue(value);

                            // NavigatorUtil.goSocialPostDetail(context, item);
                          },
                          trailing: arrowRight(),
                        );
                      },
                      separatorBuilder: (context, index) {
                        return Divider(
                          height: 1,
                          indent: 12,
                          endIndent: 12,
                        );
                      },
                      itemCount: snapshot.data.pageResult.results.length,
                    )
              : Container()
          : Container(),
    );
  }

  Widget buildResults(BuildContext context) {
    return p.ProviderWidget<SocialDetailModel>(
      model: _searchModel,
      autoDispose: false,
      builder: (_, model, __) {
        return EasyRefresh.custom(
          controller: model.refreshController,
          enableControlFinishRefresh: true,
          enableControlFinishLoad: true,
          onLoad: model.isIdle ? () => model.loadMore() : null,
          header: buildClassicalHeader(),
          footer: buildClassicalFooter(),
          slivers: <Widget>[
            if (model.isBusy)
              SliverToBoxAdapter(
                child: RequestLoadingWidget(),
              ),
            if (model.isEmpty)
              SliverToBoxAdapter(
                child: RequestErrorWidget(
                  null,
                  msg: "暂时找不到您想搜索的东西喔",
                  assets: RequestErrorWidget.ASSETS_NO_MOTION,
                ),
              ),
            if (model.isIdle)
              SliverList(
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    Post post = model.list[index];
                    return PostWidget(
                      post,
                      _searchModel,
                      selfId == post.userId,
                      keyword: _controller.text,
                      highlight: true,
                    );
                  },
                  childCount: model.list.length,
                ),
              ),
          ],
        );
      },
    );
  }
}
