import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/entity/user_me_entity.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: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/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/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';

import '../../../components/newfeed_card_header.dart';
import '../../../components/newsfeed_card_content.dart';
import '../../../components/newsfeed_card_footer.dart';
import '../../../router/page/community_page_router.dart';
import '../community_page.dart';
import '../community_pageview_idx_data.dart';
import '../community_vm.dart';
import 'foryou_vm.dart';

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

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


  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.read(foryouVmProvider.notifier);
    final state = ref.watch(foryouVmProvider);
    useEffect((){
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() => vm.initPageData());
      return () {
        // 组件卸载时执行
      };
    }, []);
    return Scaffold(
      // appBar: MyAppBar.appBar(
      //   context,
      //   "foryou",
      //   backgroundColor: context.appColors.whiteBG,
      // ),
      backgroundColor: DarkThemeUtil.multiColors(context, ColorUtils.string2Color("#F2F3F6"), darkColor: Colors.black),
        body: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            Expanded(
              child: EasyRefresh(
                controller: vm.refreshController,
                key: const PageStorageKey<String>('news'),
                onLoad: () async{
                  Log.d("--foryou--onLoad");
                  vm.loadMore();
                },
                onRefresh: () async{
                  Log.d("--foryou--onRefresh");
                  vm.onRefresh();
                },
                child: LoadStateLayout(
                  state: state.loadingState,
                  errorMessage: state.errorMessage,
                  errorRetry: () {
                    vm.retryRequest();
                  },
                  successSliverWidget: [
                    SliverList(
                      delegate: SliverChildBuilderDelegate(
                              (context, index){
                            return _buildNewsItem(context, ref, state.list![index], vm, index);
                          },
                          childCount: state.list!.length
                      ),
                    )
                  ],
                ),
              ),
            )
          ],
        )
    );
  }

  Widget _buildNewsItem(BuildContext context, WidgetRef ref, Map<String, dynamic> item, vm, int itemIdx){
    UserMeEntity userInfo = UserConfigService.getState().user as UserMeEntity;
    int? user_id = int.tryParse(userInfo?.id ?? "");
    String card_title = item.getValue("title", "");
    int card_id = item.getValue("id", null);
    String card_created_at = item.getValue("created_at", "");
    Map<String, dynamic>? card_account = item.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 = item.getValue("content", "");
    List? card_resources = item.getValue<List>("resources", [])?? [];
    bool card_liked = item.getValue("liked", false);
    int card_likes_count = item.getValue("likes_count", 0);
    int card_comments_count = item.getValue("comments_count", 0);

    return Container(
      margin: const EdgeInsets.only(left: 15, right: 15,top: 14,bottom: 0),
      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: Stack(
        children: [
          Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 卡片头部(头像 标题 时间)
                Container(
                  child: NewsFeedCardHeader(
                    key: UniqueKey(),
                    title: card_count_name,
                    avator: card_avatar,
                    time: card_created_at,
                  ),
                ),
                const SizedBox(height: 15),
                // 卡片中间 （文字和图片）
                NewsFeedCardContent(
                  key: UniqueKey(),
                  content: card_content,
                  imageUrls: card_resources,
                ),
                const SizedBox(height: 16),
                // // 卡片底部 (点赞 评论 分享)
                Container(
                  padding: const EdgeInsets.only(top: 10, bottom: 15),
                  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, itemIdx);
                    },
                    onComment: (){
                      vm.handlerClickActionBtn('comments', item, itemIdx);
                    },
                    onShare: (){
                      vm.handlerClickActionBtn('share', item, itemIdx);
                    },
                  ),
                ),
              ]
          ),
          // 右上角 关注/取消关注 按钮
          Visibility(
            visible: card_count_id != null && card_count_id != user_id,
            child: Positioned(
                right: 0,
                top: 0,
                child: Container(
                  width: 83.5,
                  height: 45.5,
                  alignment: Alignment.center,
                  // decoration: BoxDecoration(
                  //   color:  context.appColors.textPrimary,
                  //   borderRadius: BorderRadius.circular(5),
                  // ),
                  child: MyButton(
                    text: card_followed ? S.current.followed:S.current.to_follow,
                    textColor: card_followed ?  context.appColors.disEnableGray: context.appColors.textWhite,
                    disabledTextColor: context.appColors.disEnableGray,
                    backgroundColor: card_followed ? Colors.transparent : context.appColors.textPrimary,
                    side: BorderSide(color: !card_followed ? 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,  card_followed );
                      // if(asyncResult){
                      //   // 成功  关注->取消关注  取消关注->关注
                      // }
                    },
                  ),
                )
            ),
          )
        ],
      ),
    ).constrained(
      width: double.infinity,
      // height: 580,
      // minHeight: 300,
    ).onTap((){
      vm.handlerGotoDetail(context, item['id']);
    });
  }

}