import 'package:cpt_community/components/comments_dialog.dart';
import 'package:cpt_community/modules/my_posts/my_posts_newsfeed/my_posts_newsfeed_vm.dart';
import 'package:cpt_community/router/page/community_page_router.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:domain/entity/myposts_newsfeed_entity.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:plugin_basic/provider/app_config/app_config_service.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:shared/utils/ext_dart.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';

import '../../../components/newsfeed_card_content.dart';
import '../../../components/newsfeed_card_footer.dart';
import '../my_posts_tabs.dart';
import 'newsfeed_itemgroup_state.dart';
import 'newsfeed_sticky_header.dart';

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

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.read(myPostsNewsfeedVmProvider.notifier);
    useEffect((){
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() => vm.initPageData());
      return null;
    },[]);

    return Scaffold(
      // appBar: MyAppBar.appBar(
      //   context,
      //   "My Posts",
      //   backgroundColor: context.appColors.whiteBG,
      // ),
      // backgroundColor: context.appColors.backgroundDefault,
      backgroundColor: DarkThemeUtil.multiColors(context, ColorUtils.string2Color("#F2F3F6"), darkColor: Colors.black),
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Column(
          children: [
            // _buildHeaderTabs(context, ref),
            _buildContentBody(context, ref),
          ],
        ),
      ),
    );
  }

  Widget _buildHeaderTabs(BuildContext context, WidgetRef ref) {
    final state = ref.watch(myPostsNewsfeedVmProvider);
    final vm = ref.read(myPostsNewsfeedVmProvider.notifier);
    return Container(
        color: DarkThemeUtil.multiColors(context, Colors.blue,darkColor: Colors.black),
        child: MyPostsTab(
          key: UniqueKey(),
          tabsList: state.tabsList!,
          tabsRouter: null,
          onClickAction:(activeTabIdx){
            Log.d("点击的tab index: $activeTabIdx");
            vm.handlerChangeTab(context, activeTabIdx);
          },
        ),
    );
  }

  Widget _buildContentBody(BuildContext context, WidgetRef ref) {
    final vm = ref.read(myPostsNewsfeedVmProvider.notifier);
    final state = ref.watch(myPostsNewsfeedVmProvider);
    return Expanded(
      child: Container(
        // color: Colors.red,
        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 StickyHeader(
                        header: _buildHeaderContent(state.list![index], context),
                        content: Column(
                          children: _buildGroupItemContent((state.list![index] as NewsFeedItemGroupState).itemgroupDatas as List<MypostsNewsfeedList>, index, vm, context),
                        ),
                      );
                    },
                    childCount: state.list!.length,
                  ))
            ]
          )
        ),
      ),
    );
  }

  Widget _buildHeaderContent(NewsFeedItemGroupState itemGroupDatas, BuildContext context,) {
    String groupId = itemGroupDatas.groupId;
    return Container(
      padding: const EdgeInsets.only(left: 15, right: 15,),
      // color: context.appColors.backgroundDefault,
      color: DarkThemeUtil.multiColors(context, ColorUtils.string2Color('#F2F3F6'),darkColor: Colors.black),
      child: NewsFeedStickyHeader(title: groupId,),
    );
  }

  List<Widget> _buildGroupItemContent(List<MypostsNewsfeedList> groupList, int groupIndex,  vm, BuildContext context) {
    return groupList.asMap().entries.map((entry) {
      int childIndex = entry.key;
      MypostsNewsfeedList item = entry.value;
      Map<String, dynamic> itemJson = entry.value.toJson();

      // String card_title = item.getValue("title", "");
      int card_id = itemJson.getValue("id", null);
      String card_created_at = itemJson.getValue("created_at", "");
      // Map<String, dynamic>? card_account = itemJson.getValue<Map<String,dynamic>>("account", null);
      // String card_avatar = card_account?['avatar']?? "";
      // String card_count_name = card_account?['name']?? "";
      // bool card_followed = card_account?['followed']??false;
      // int card_count_id = card_account?['id']?? null;
      String card_content = itemJson.getValue("content", "");
      List? card_resources = itemJson.getValue<List>("resources", [])?? [];
      bool card_liked = itemJson.getValue("liked", false);
      int card_likes_count = itemJson.getValue("likes_count", 0);
      int card_comments_count = itemJson.getValue("comments_count", 0);

      return Container(
        margin: const EdgeInsets.only(left: 15, right: 15,top: 14,bottom: 14),
        padding: const EdgeInsets.only(left: 15, right: 15,top: 17,bottom: 0),
        decoration: BoxDecoration(
            color: context.appColors.textWhite,
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(
                color: ColorUtils.string2Color("#E4E7EB").withOpacity(0.5),
                spreadRadius: 0,
                blurRadius: 4,
                offset: const Offset(0, 4), // changes position of shadow
              ),
            ]
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            MyTextView(
              card_created_at,
              textColor: context.appColors.textDarkGray,
              fontSize: 12,
              paddingLeft: 15,
              marginBottom: 12.5,
              isFontMedium: true,
            ),
            // 卡片中间 （文字和图片）
            NewsFeedCardContent(
              key: UniqueKey(),
              content: card_content,
              imageUrls: card_resources,
            ),
            const SizedBox(height: 16),
            // 卡片底部 (点赞 评论 分享)
            Container(
              padding: const EdgeInsets.only(top: 10, bottom: 10),
              decoration: BoxDecoration(
                // color: Colors.white,
                  border: Border(
                    top: BorderSide(color: context.appColors.dividerDefault, width: 0.5),
                  )
              ),
              child: NewsFeedCardFooter(
                key: UniqueKey(),
                isLike: card_liked,
                likes_count: card_likes_count,
                comments_count: card_comments_count,
                onLike: () {
                  vm.handlerClickActionBtn('like', item.toJson(), groupIndex, childIndex);
                },
                onComment: () {
                  vm.handlerClickActionBtn('comments', item.toJson(), groupIndex, childIndex);
                },
                onShare: () {
                  vm.handlerClickActionBtn('share', item.toJson(), groupIndex, childIndex);
                },
              ),
            ),
          ],
        ),
      ).onTap((){
        // 跳转到 详情页
        vm.handlerGotoDetail(context, card_id);
      });
    }).toList();
  }
}
