import 'package:cpt_community/modules/my_following/my_following_vm.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/my_appbar.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:widgets/search_app_bar.dart';
import 'package:widgets/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';

import '../../../router/page/community_page_router.dart';
import '../components/item_following.dart';
import '../components/item_following_vm.dart';
import 'my_follower_vm.dart';

@RoutePage()
class MyFollowerPage extends HookConsumerWidget {
  const MyFollowerPage({Key? key}) : super(key: key);

  //启动当前页面
  static void startInstance({BuildContext? context}) {
    if (context != null) {
      context.router.push(const MyFollowerPageRoute());
    } else {
      appRouter.push(const MyFollowerPageRoute());
    }
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.read(myFollowerVmProvider.notifier);
    final state = ref.watch(myFollowerVmProvider);

    final useSearchBar = useState(false);
    // 用于存储前一次的滚动位置
    final previousOffset = useState(0.0);

    useEffect(() {
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() => vm.initPageData());
      return () {
        // 组件卸载时执行
      };
    }, []);

    useEffect((){
      Log.d("---useSearchBar.value 变化为：---${useSearchBar.value}");
      ref.read(myFollowingVmProvider.notifier)!.handlerChangeFollowerPageNavbar(useSearchBar.value);
    }, [useSearchBar.value]);


    return  Scaffold(
      // appBar: MyAppBar.appBar(
      //   context,
      //   "following",
      //   backgroundColor: context.appColors.whiteBG,
      // ),
        backgroundColor: DarkThemeUtil.multiColors(context, ColorUtils.string2Color("#F2F3F6"), darkColor: Colors.black),
        body: Container(
          height: double.infinity,
          width: double.infinity,
          color: context.appColors.whiteBG,
          child: NotificationListener<ScrollNotification>(
            onNotification: (ScrollNotification notification) {
              if (notification is ScrollUpdateNotification) {
                final ScrollMetrics metrics = notification.metrics;
                final double currentOffset = metrics.pixels;
                final double prevOffset = previousOffset.value;
                // Log.d("---最大滚动距离-----${metrics.maxScrollExtent}-------");
                if (currentOffset > prevOffset) {
                  // 向上滚动
                  // 当前滚动偏移量和前一次滚动偏移量
                  // Log.d('--向上滚动---当前currentOffset: $currentOffset, previousOffset: $prevOffset---------');
                  if(useSearchBar.value == false && metrics.maxScrollExtent >=0 && currentOffset >= 110){
                    // 滚动到110 时 将 titlebar 换成 searchbar
                    useSearchBar.value = true;
                  }
                } else if (currentOffset < prevOffset) {
                  // 向下滚动
                  // 当前滚动偏移量和前一次滚动偏移量
                  // Log.d('--向下滚动---当前currentOffset: $currentOffset, previousOffset: $prevOffset---------');
                  if(useSearchBar.value == true && metrics.maxScrollExtent >=0 && currentOffset <= 110){
                    // 滚动到110 时 将 searchbar 换成 titlebar
                    useSearchBar.value = false;
                  }
                }
                // 更新前一次的滚动位置
                previousOffset.value = currentOffset;
              }

              return false;
            },
            child: EasyRefresh(
              controller: vm.refreshController,
              // 上拉加载
              onLoad: () async{
                Log.d("----onLoad");
                vm.loadMore();
              },
              // 下拉刷新
              onRefresh: () async{
                Log.d("----onRefresh");
                vm.onRefresh();
              },
              child: LoadStateLayout(
                state: state.loadingState,
                errorMessage: state.errorMessage,
                errorRetry: () {
                  vm.retryRequest();
                },
                successSliverWidget:[
                  SliverList(
                      delegate: SliverChildBuilderDelegate(
                              (context, index){
                            return Padding(
                              padding: const EdgeInsets.only(top: 10, bottom: 10, left: 10),
                              child: SearchAppBar(
                                hintText: S.current.search,
                                onChanged: (String value){
                                  vm.handlerSearchChange(value);
                                },
                                onSearch: (String value){
                                  vm.handlerSubmitSearch(value);
                                },
                              ),
                            );
                          },
                          childCount: 1
                      )
                  ),
                  SliverList(
                      delegate: SliverChildBuilderDelegate(
                              (context, index){
                            return _buildFollowItem(context, ref, state.list![index], vm, index, state.list.length);
                          },
                          childCount: state.list!.length
                      )
                  )
                ],
              ),
            ).marginOnly(left: 15,right: 15,top: 15,bottom: 15),
          ),
        )
    );
  }

  Widget _buildFollowItem(BuildContext context,WidgetRef ref, item, vm, index, totalIndex) {
    bool isLast = index == totalIndex - 1;
    return MyFollowingListItem(
        itemObj: item,
        itemType: MyFollowingType['isFollowerType'],
        hasBottomDriver: isLast? false : true,
        onClickAction:(itemObj){
          print("点击了  ${itemObj['name']}");
        }
    );
  }
}