import 'package:cpt_community/router/page/community_page_router.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:domain/entity/newsfeed_detail_entity.dart';
import 'package:domain/entity/user_me_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.dart';
import 'package:plugin_basic/provider/user_config/user_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_button.dart';
import 'package:widgets/my_like_button.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';
import 'package:widgets/my_button.dart';

import '../../../components/newfeed_card_header.dart';
import '../../../components/newsfeed_card_content.dart';
import '../../../components/newsfeed_card_footer.dart';
import 'newsfeed_detail_state.dart';
import 'newsfeed_detail_vm.dart';

@RoutePage()
class NewsfeedDetailPage extends HookConsumerWidget {
  final int? id;
  final String? type;  // news  following foryou  mypostsNews

  const NewsfeedDetailPage({Key? key, @PathParam('id') required this.id, @PathParam('type') required this.type}) : super(key: key);
  // 启动当前页面
  static void startInstance({BuildContext? context, int? id, String? type = 'news'}) {
    if (context != null) {
      context.router.push(NewsfeedDetailPageRoute(id: id, type: type));
    } else {
      appRouter.push(NewsfeedDetailPageRoute(id: id, type: type));
    }
  }


  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.read(newsfeedDetailVmProvider.notifier);
    final state = ref.watch(newsfeedDetailVmProvider);
    GlobalKey _likeButtonKey = GlobalKey<MyLikeButtonState>();

    NewsfeedDetailEntity?  detailInfo = state.detailInfo!;

    List<NewsfeedDetailComments>? commentList = detailInfo!.comments;

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


    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        S.current.news_feed_detail,
        backgroundColor: context.appColors.backgroundWhite,
      ),
      backgroundColor: DarkThemeUtil.multiColors(context, ColorUtils.string2Color("#F2F3F6"), darkColor: Colors.black),
      body: Column(
          mainAxisSize: MainAxisSize.max,
          children:[
            Expanded(
                child: EasyRefresh(
                  controller: vm.refreshController,
                  // 上拉加载
                  onLoad: () async{
                    Log.d("----onLoad");
                    vm.loadMore(id:id, type: type);
                  },
                  // 下拉刷新
                  onRefresh: () async{
                    Log.d("----onRefresh");
                    vm.onRefresh(id:id, type: type);
                  },
                  child: LoadStateLayout(
                    state: state.loadingState,
                    errorMessage: state.errorMessage,
                    errorRetry: () {
                      vm.retryRequest(id:id, type: type);
                    },
                    successSliverWidget: [
                      SliverList(
                        delegate: SliverChildListDelegate(
                            [
                              _buildTopCard(context, ref, detailInfo),
                              ConstrainedBox(
                                constraints: BoxConstraints(
                                  minHeight: MediaQuery.of(context).size.height - 250 - 150,
                                ),
                                child: _buildCommentListCard(context, ref, detailInfo),
                              )
                            ]
                        ),
                      )
                    ],
                  ),
                ),
              ),
            (detailInfo != null && detailInfo.id != null)? _buildBottomActionSection(context, ref,vm, _likeButtonKey): SizedBox.shrink(),
          ]
      )
    );
  }

  Widget _buildTopCard(BuildContext context, WidgetRef ref,NewsfeedDetailEntity detailInfo ){
    final vm = ref.read(newsfeedDetailVmProvider.notifier);
    UserMeEntity userInfo = UserConfigService.getState().user as UserMeEntity;
    int? user_id = int.tryParse(userInfo?.id ?? "");
    String card_title = "";
    int card_id = detailInfo!.id??0;
    String card_created_at = detailInfo!.createdAt ?? "";
    NewsfeedDetailAccount card_account = detailInfo!.account?? NewsfeedDetailAccount();
    int card_count_id = card_account!.id??0;
    String card_avator = card_account!.avatar?? '';
    String card_count_name = card_account!.name?? '';
    bool card_followed = card_account!.followed??false;
    String card_content = detailInfo!.content??"";
    bool? card_liked = detailInfo!.liked;
    num card_likes_count = detailInfo!.likesCount?? 0;
    num card_comments_count = detailInfo!.commentsCount?? 0;
    List? card_resources = detailInfo!.resources?? [];


    return Stack(
      children: [
        Container(
          margin: const EdgeInsets.only(left: 15, right: 15,top: 14,bottom: 0),
          padding: const EdgeInsets.only(left: 15, right: 15,top: 17,bottom: 17),
          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: [
                // 卡片头部(头像 标题 时间)
                NewsFeedCardHeader(
                  key: UniqueKey(),
                  title: card_count_name,
                  avator: card_avator,
                  time: card_created_at,
                ),
                const SizedBox(height: 15),
                // 卡片中间 （文字和图片）
                NewsFeedCardContent(
                  key: UniqueKey(),
                  content: card_content,
                  imageUrls: card_resources,
                    textMaxLines: 5000,
                ),
                const SizedBox(height: 26),
              ]
          ),
        ),
        // 右上角 关注/取消关注 按钮
        Visibility(
          visible: card_count_id != null && card_count_id != user_id,
          child: Positioned(
              right: 30,
              top: 35,
              child: Container(
                width: 83.5,
                height: 45.5,
                alignment: Alignment.center,
                // decoration: BoxDecoration(
                //   color:  context.appColors.textPrimary,
                //   borderRadius: BorderRadius.circular(5),
                // ),
                child: HookBuilder(
                    builder: (context) {
                      final isFollowedState = useState<bool>(card_followed);
                      return MyButton(
                        text: isFollowedState.value ?  S.current.followed:S.current.to_follow,
                        textColor: DarkThemeUtil.multiColors(context, isFollowedState.value ? context.appColors.disEnableGray: context.appColors.textWhite, darkColor: isFollowedState.value ? context.appColors.textWhite: context.appColors.textWhite),
                        disabledTextColor: context.appColors.disEnableGray,
                        backgroundColor: DarkThemeUtil.multiColors(context, isFollowedState.value ? Colors.transparent : context.appColors.textPrimary, darkColor: isFollowedState.value ? Colors.white38 : AppColorsTheme.colorPrimary),
                        side: BorderSide(color: !isFollowedState.value ? Colors.transparent : context.appColors.disEnableGray, width: 0.5),
                        radius: 8,
                        minHeight: 27.5,
                        padding: const EdgeInsets.only(left: 5, right: 5,top:9,bottom:9),
                        fontWeight: FontWeight.w400,
                        fontSize: 14,
                        onPressed: () async{
                          bool asyncResult = await vm.handlerFollow(context,card_count_id, card_id,  isFollowedState.value );
                          if(asyncResult){
                            // 成功  关注->取消关注  取消关注->关注
                            isFollowedState.value = !isFollowedState.value;
                          }
                        },
                      );
                    }
                ),
              )
          ),
        )
      ],
    );
  }

  Widget _buildCommentListCard(BuildContext context,  WidgetRef ref, NewsfeedDetailEntity detailInfo){
    final vm = ref.read(newsfeedDetailVmProvider.notifier);
    int likeCount = detailInfo!.likesCount??0;
    List<NewsfeedDetailComments>? commentList = detailInfo!.comments;
    num commentCount = commentList?.length?? 0;
    return HookBuilder(
      builder: (context) {
        return Container(
          margin: const EdgeInsets.only(left: 15, right: 15,top: 15,bottom: 18),
          padding: const EdgeInsets.only(bottom: 30),
          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(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              // 总评论数 总收藏数等
              Row(
                children: [
                  Expanded(
                    child: Container(
                      padding: const EdgeInsets.only(left: 15, right: 15,top: 14,bottom: 14),
                      child: Row(
                        children: [
                          MyTextView(S.current.comment_count(commentCount),  textColor: context.appColors.textPrimary, fontSize: 15, isFontLight: true,),
                        ]
                      )
                    )
                  ),
                 // 收藏数
                 Expanded(
                     child: Container(
                       padding: const EdgeInsets.only(right: 20),
                       child: Row(
                         mainAxisAlignment: MainAxisAlignment.end,
                         children: [
                           const MyAssetImage(
                             Assets.communityLikeActive,
                             width: 15,
                             height: 15,
                           ),
                           const SizedBox(width: 5,),
                           MyTextView(
                             '${likeCount}',
                             textColor: ColorUtils.string2Color("#767676"),
                             fontSize: 14,
                             isFontLight: true,
                           ),
                         ],
                       ),
                     ),
                 )
                ],
              ),

              // 分割线
              Container(
                height: 1,
                color: context.appColors.dividerDefault,
              ),

              Padding(
                padding: const EdgeInsets.only(top: 16),
                child: Column(
                  children: (commentList?.isNotEmpty ?? false)? commentList!.asMap().entries.map((entry) {
                    NewsfeedDetailComments item = entry.value;
                    final index = entry.key;
                    final lastIdx = commentList.length - 1;
                    int newsfeedId = detailInfo!.id!;
                    int to_user_id = item.id!;
                    String to_user_name = item!.account!.name!;
                    return _buildCommentItem(context, ref, item, index, lastIdx).onTap((){
                      // 点击 单条 评论 则对 此评论进行评论
                      vm.handlerCommentClick(context, newsfeedId, to_user_id, to_user_name, true);
                    });
                  }).toList(): [
                    // 没有数据的显示
                    const Center(
                      child: SizedBox(
                        height: 250,
                        child: MyAssetImage(Assets.baseServicePageNoData, width: 123.5, height: 115.5, fit: BoxFit.contain),
                      ),
                    )
                  ],
                ),
              ),
            ]
          ),
        ).borderRadius(all:8);
      }
    );
  }


  Widget _buildCommentItem(BuildContext context, WidgetRef ref, item, index, lastIdx){
    final vm = ref.read(newsfeedDetailVmProvider.notifier);
    final state = ref.watch(newsfeedDetailVmProvider);
    final detailInfo = state.detailInfo!;
    List<NewsfeedDetailComments>? commentList = detailInfo!.comments;
    num commentCount = commentList?.length?? 0;

    NewsfeedDetailComments? comment_Item = commentList?[index];
    int  comment_id = comment_Item!.id?? 0;
    String comment_content = comment_Item!.content?? '';

    String comment_time = comment_Item!.createdAt?? '';
    NewsfeedDetailCommentsAccount? commentAccount_Item = commentList?[index].account;
    String comment_avatar = commentAccount_Item?.avatar?? '';
    int comment_account_id = commentAccount_Item?.id?? 0;
    String comment_name = commentAccount_Item?.name?? "";

    NewsfeedDetailCommentsToAccount? commentToAccount_Item = commentList?[index].toAccount;
    String comment_toAccount_avatar = commentToAccount_Item?.avatar?? '';
    int comment_toAccount_id = commentToAccount_Item?.id?? 0;
    String comment_toAccount_name = commentToAccount_Item?.name?? "";

    if(commentToAccount_Item !=null && comment_toAccount_name != null){
      comment_content = '@$comment_toAccount_name: $comment_content';
    }


    return Container(
      padding: const EdgeInsets.only(left: 20,right: 20),
      margin:  EdgeInsets.only(top: index> 0? 16: 0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        children: [
          MyLoadImage(
            comment_avatar,
            width: 43,
            height: 43,
            isCircle: true,
            fit: BoxFit.cover,
          ).onTap(() {
            // 点击头像
            // onTap?.call();
          }),
          Expanded(
            child: Container(
              padding: const EdgeInsets.only(left:15, right: 0),
              // color: Colors.red,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  MyTextView(
                    comment_name,
                    isFontRegular: true,
                    fontSize: 14,
                    textColor: context.appColors.textPrimary,
                    maxLines: 1,
                    isTextEllipsis: true,
                  ),
                  MyTextView(
                    comment_time,
                    isFontLight: true,
                    fontSize: 12,
                    marginTop: 10,
                    textColor: ColorUtils.string2Color('#767676'),
                    maxLines: 1,
                    isTextEllipsis: true,
                  ),
                  MyTextView(
                    comment_content,
                    isFontLight: true,
                    fontSize: 15,
                    marginTop: 10,
                    textColor: context.appColors.textBlack,
                    maxLines: null,
                    isTextEllipsis: false,
                  ),

                 const SizedBox(height: 15,),
                 // 分割线
                  index!=lastIdx?Container(height: 1, color: context.appColors.dividerDefault):const SizedBox.shrink(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }


  Widget _buildBottomActionSection(BuildContext context, WidgetRef ref ,vm,  _likeButtonKey){
    final state = ref.watch(newsfeedDetailVmProvider);
    final vm = ref.read(newsfeedDetailVmProvider.notifier);

    NewsfeedDetailEntity  detailInfo = state.detailInfo!;

    int newsfeedId = detailInfo!.id!;

    int to_user_id = detailInfo!.account!.id!;
    String to_user_name = detailInfo!.account!.name!;

    // List<NewsfeedDetailComments>? commentList = detailInfo!.comments;

    bool isLike = detailInfo!.liked?? false;

    return SafeArea(
      bottom: true,
      child: Visibility(
        visible: state.loadingState == LoadState.State_Success,
        child: Container(
            height: 60,
            width: MediaQuery.of(context).size.width,
            color: DarkThemeUtil.multiColors(context, context.appColors.textPrimary, darkColor: Colors.black),
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          alignment: Alignment.center,
                          padding: const EdgeInsets.only(left: 10,right: 10),
                          child: Wrap(
                            alignment: WrapAlignment.center,
                            runAlignment: WrapAlignment.center,
                            children: [
                              MyLikeButton(
                                key: _likeButtonKey,
                                isLiked: isLike,
                                isCustomIcon: true,
                                customIconWidth: 20,
                                customIconHeight: 18,
                                customIconActiveAssets: Assets.communityLikeActive,
                                customIconUnActiveAssets: Assets.communityNewsfeedDetailLike,
                                onLike: () async {
                                  Log.d('点击了like button');
                                  final asyncResult = await vm.handlerLikeClick(context, detailInfo!.id as int, isLike);
                                },
                              ),
                              const SizedBox(width: 10,),

                              MyTextView(
                                S.current.like,
                                textColor: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: Colors.white),
                                fontSize: 14,
                                isFontRegular: true,
                              )
                            ],
                          ),
                        ).onTap((){
                          final state = _likeButtonKey.currentState;
                          state?.triggerTap();
                        })
                      ],
                    ),
                  ),
                  Expanded(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          height: 40,
                          alignment: Alignment.center,
                          padding: const EdgeInsets.only(left: 10,right: 10),
                          child: Wrap(
                            // alignment: WrapAlignment.center,
                            runAlignment: WrapAlignment.center,
                            children: [
                              // MyLoadImage(
                              //   Assets.communityNewsfeedDetailComment,
                              //   width: 17.5,
                              //   height: 16.5,
                              // ),
                              const MyAssetImage(
                                Assets.communityNewsfeedDetailComment,
                                width: 17.5,
                                height: 16.5,
                              ),
                              const SizedBox(width: 10,),
                              MyTextView(
                                S.current.comment,
                                textColor: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: Colors.white),
                                fontSize: 14,
                                isFontRegular: true,
                              ),
                            ],
                          ),
                        ).onTap((){
                          vm.handlerCommentClick(context, newsfeedId, to_user_id, to_user_name, false);
                        })
                      ],
                    ),
                  ),
                ]
            )
        ),
      ),
    );
  }
}
