import 'package:cpt_services/components/chooseAirConditionContent.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/paid_service_detail_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/app_config/app_config_service.dart';
import 'package:plugin_platform/engine/image/image_preview.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:shared/utils/size_config.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_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:shared/utils/richText_utils.dart';

import '../../../components/chooseHouseCleanContent.dart';
import '../../../components/user_evaluate_card_item.dart';
import '../../../constants_services.dart';
import 'service_clean_detail_vm.dart';

import '../../../router/page/services_page_router.dart';

@RoutePage()
class ServiceCleanDetailPage extends HookConsumerWidget {
  final int id;
  final int? cleanServiceTypeId;
  bool liked = false;
  int likesCount = 0;

  ServiceCleanDetailPage({Key? key,@PathParam('id') required this.id, @PathParam('cleanServiceTypeId') this.cleanServiceTypeId, required this.liked, required this.likesCount}) : super(key: key);
  // 启动当前页面
  static void startInstance({BuildContext? context, int? id, int? cleanServiceTypeId, bool? liked, int? likesCount}) {
    if (context != null) {
      context.router.push(ServiceCleanDetailPageRoute(id: id!, cleanServiceTypeId: cleanServiceTypeId!, liked: liked!, likesCount: likesCount = 0));
    } else {
      appRouter.push(ServiceCleanDetailPageRoute(id: id!, cleanServiceTypeId: cleanServiceTypeId!, liked: liked!, likesCount: likesCount = 0));
    }
  }


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

    PaidServiceDetailEntity? detailInfo = state.datas?? null;


    useEffect((){
      vm.setInitPageData(id: id, cleanServiceTypeId: cleanServiceTypeId, liked: liked, likesCount: likesCount);

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

    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        S.current.clean_detail,
        backgroundColor: context.appColors.backgroundWhite,
      ),
      backgroundColor: context.appColors.backgroundWhite,
      body: Column(
        children: [
          Expanded(
            child: EasyRefresh(
              controller: vm.refreshController,
              // 上拉加载
              onLoad: null,
              // 下拉刷新
              onRefresh: () async{
                Log.d("----onRefresh");
                vm.onRefresh();
              },
              // header: MaterialHeader(),
              child: Stack(
                  children:[
                    LoadStateLayout(
                      state: state.loadingState,
                      errorMessage: state.errorMessage,
                      errorRetry: () {
                        vm.retryRequest();
                      },
                      // successWidget: SingleChildScrollView(
                      //   scrollDirection: Axis.vertical,
                      //   physics: const BouncingScrollPhysics(),
                      //   clipBehavior: Clip.none,
                      //   child: _buildContentBox(context, ref, detailInfo,),
                      // ),
                      successSliverWidget: [
                        SliverList(
                          delegate: SliverChildBuilderDelegate(
                                  (context, index){
                                return detailInfo !=null ? _buildContentBox(context, ref, detailInfo): Container();
                              },
                              childCount: 1
                          ),
                        )
                      ],
                    ),
                  ]
              ),
            ),
          ),
          // 底部联系信息
          Visibility(
            visible: state.loadingState == LoadState.State_Success,
            child: detailInfo !=null ? _buildBottomConcatInfo(context, ref, _likeButtonKey,
              detailInfo:detailInfo,
            ): Container(),
          )
        ],
      ),
    );
  }

  Widget _buildContentBox(BuildContext context, WidgetRef ref, PaidServiceDetailEntity detailInfo) {
    final String title = detailInfo?.name??'';
    List<String> resources = detailInfo!.resources?.cast<String>()??[];
    double evaluationsAvgScore = (detailInfo?.evaluationsAvgScore?? 5.0).toDouble();
    final hilightStr = detailInfo?.highlight??'';
    final description =  RichtextUtils.getHandleResult(detailInfo?.description??'');

    final String merchantName = detailInfo?.merchant?.name??'';

    List<dynamic> evaluations = detailInfo?.evaluations??[];
    bool hasEvaluations = evaluations.isNotEmpty;
    CarouselSliderController buttonCarouselController = CarouselSliderController();

    return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图片
          SizedBox(
            width: SizeConfig().screenWidth,
            height: 175,
            child: CarouselSlider(
              items: resources.map((resource) => MyLoadImage(
                  resource,
                  fit: BoxFit.cover, // 确保图片覆盖整个区域
                  width: SizeConfig().screenWidth, // 确保图片宽度与屏幕宽度一致
                  height: 175, // 确保图片高度与 CarouselSlider 高度一致
                ).onTap((){
                  ImagePreviewEngine.multipleImagePreview(
                      context,
                      resources,
                      heroes: List.generate(resources.length, (index) => resources[index]),
                      onLongPressAction: (url) {}
                  );
                })
              ).toList(),
              carouselController: buttonCarouselController,
              options: CarouselOptions(
                autoPlay: false,
                enlargeCenterPage: true,
                viewportFraction: 1,
                initialPage: 0,
              ),
            ),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 亮点
              Padding(
                padding: const EdgeInsets.only(left: 16, right: 16, top: 16,),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const MyAssetImage(
                      Assets.serviceHighlightIcon,
                      width: 9,
                      height: 13,
                    ),
                    hilightStr.isNotEmpty? MyTextView(
                      hilightStr,
                      fontSize: 13,
                      isFontRegular: true,
                      isTextEllipsis: true,
                      maxLines: 2,
                      textColor: context.appColors.textDarkGray,
                      marginLeft: 5,
                    ).expanded():const SizedBox.shrink(),
                  ],
                ),
              ),
              //  评分
              Column(
                children: [
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.only(left: 16, right: 16, top: 16,bottom: 16),
                    color: context.appColors.whiteBG,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        MyTextView(
                          '$title',
                          textColor: context.appColors.textBlack,
                          fontSize: 18,
                          isFontBold: true,
                          marginBottom: 5,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            AnimatedRatingStars(
                              initialRating: evaluationsAvgScore,
                              onChanged: (rating) {
                              },
                              readOnly: true,
                              displayRatingValue: true, // Display the rating value
                              interactiveTooltips: true, // Allow toggling half-star state
                              customFilledIcon: Icons.star,
                              customHalfFilledIcon: Icons.star_half,
                              customEmptyIcon: Icons.star_border,
                              filledColor: ColorUtils.string2Color("#FF0000"),
                              starSize: 16.5,
                              animationDuration: const Duration(milliseconds: 0),
                              animationCurve: Curves.easeInOut,
                            ),
                            MyTextView(
                              "${evaluationsAvgScore}",
                              textColor: context.appColors.textBlack,
                              fontSize: 16,
                              isFontMedium: true,
                              marginLeft: 15,
                            ),
                          ],
                        ),
                        MyTextView(
                          merchantName,
                          textColor: context.appColors.textDarkGray999,
                          fontSize: 12,
                          isFontRegular: true,
                          marginTop: 10,
                          marginBottom: 5,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              //  室内清洁选择服务 或者 空调清洁选择空调选项
              _buildSelectHouseCleanOrAirConditioner(context, ref, detailInfo),
              // user Reviews
              hasEvaluations? _buildUserReviews(context, ref, detailInfo): const SizedBox.shrink(),
              // description
              Html(data: description),
            ],
          ),
        ]
    );
  }

  // user Reviews
  Widget _buildUserReviews(BuildContext context, WidgetRef ref, PaidServiceDetailEntity detailInfo) {
    final vm = ref.read(serviceCleanDetailVmProvider.notifier);
    final state = ref.watch(serviceCleanDetailVmProvider);
    int reviewScoreMaxNum = 3;
    double reviewScoreItemCardHeight = 275;
    double reviewScoreItemCardWidth = 300;
    List<PaidServiceDetailEvaluations>? evaluations = detailInfo?.evaluations;

    if (evaluations == null || evaluations.isEmpty) {
      return const SizedBox.shrink();
    }else {
      if(evaluations.length >= reviewScoreMaxNum){
        reviewScoreMaxNum = reviewScoreMaxNum;
        reviewScoreItemCardWidth = 300;
      }else{
        reviewScoreMaxNum = evaluations.length;
        reviewScoreItemCardWidth = (context.screenSize.width! - 32) / reviewScoreMaxNum;
      }

      Log.d("evaluations 数量：${evaluations.length}");
      Log.d("evaluation 最大展示数量：$reviewScoreMaxNum");

      Map<String, dynamic> item = {
        'name': "User Sandy",
        'avatar': "",
        'score': 5.0,
        'card_created_at': "14 Oct 2024 15:00",
        'content': "This aunt is very careful because I haven't been home for three or four months. The house is",
        'resources': [],
      };

      return Container(
        width: context.screenSize.width! * reviewScoreMaxNum,
        height: reviewScoreItemCardHeight,
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.only(left: 16, right: 16, top: 16,bottom: 0),
              color: context.appColors.whiteBG,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  MyTextView(
                   S.current.user_reviews,
                    textColor: context.appColors.textBlack,
                    fontSize: 17,
                    isFontBold: true,
                  ),
                  Wrap(
                      crossAxisAlignment: WrapCrossAlignment.center,
                      spacing: 5,
                      children: [
                        MyTextView(
                        S.current.all,
                          textColor: context.appColors.textDarkGray999,
                          fontSize: 14,
                          isFontRegular: true,
                        ),
                        MyAssetImage(
                          Assets.serviceArrowRightIcon,
                          width: 12.5,
                          height: 10,
                          color: context.appColors.textPrimary,
                        ),
                      ]
                  ),
                ],
              ).onTap((){
                vm.gotoUserReviewsPage(context, id, cleanServiceTypeId);
              }),
            ),
            // evaluate list
            Expanded(
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                physics: const BouncingScrollPhysics(),
                child: Container(
                  color: context.appColors.whiteBG,
                  padding: const EdgeInsets.only(left: 16, right: 16, top: 0,bottom: 16),
                  child: Row(
                    children: List.generate(reviewScoreMaxNum, (index){
                      PaidServiceDetailEvaluations item = evaluations[index];
                      return _buildserviceEvaluateListItem(context, ref, item, vm, reviewScoreItemCardWidth);
                    }),
                  ),
                ),
              ),
            )
          ],
        ),
      );
    }
  }

  Widget _buildserviceEvaluateListItem(BuildContext context, WidgetRef ref, PaidServiceDetailEvaluations item, vm, double cardWidth){
    int? card_id = item.id?? null;
    double card_score = (item.score?? 5.0).toDouble();
    String card_comment = item.comment??"";
    List<String>? card_resources = (item.resources??[]).cast<String>();
    String card_created_at = item.createdAt??"";
    PaidServiceDetailEvaluationsAccount? account=item.account??null;
    String card_name = account?.name??"";
    String card_avatar = account?.avatar??"";

    // Log.d("card_resources  $card_resources");
    return LayoutBuilder(
      builder: (context, constraints) {
        final maxWidth = constraints.maxWidth;
        final maxHeight = constraints.maxHeight;
        Log.d("maxWidth  $maxWidth");
        return Container(
          margin: const EdgeInsets.only(top: 10),
          width: cardWidth,
          height: maxHeight,
          child: Container(
            margin: const EdgeInsets.only(right: 5),
            decoration: BoxDecoration(
              color: DarkThemeUtil.multiColors(context, ColorUtils.string2Color("#F8F8F8"), darkColor: Colors.white12),
              borderRadius: BorderRadius.circular(8),
              // boxShadow: [
              //   BoxShadow(
              //     color: DarkThemeUtil.multiColors(context, ColorUtils.string2Color('#E5E5E5'), darkColor: Colors.transparent)?? Colors.transparent,
              //     offset: const Offset(0, 2),
              //     blurRadius: 8,
              //   ),
              // ],
            ),
            child: Padding(
                padding: const EdgeInsets.only(left: 15, right:15,top: 17, bottom: 17),
                child: UserEvaluateCardItem(
                  key: UniqueKey(),
                  useInSence: 'cleanDetailPage',
                  name: card_name,
                  avator: card_avatar,
                  score: card_score,
                  time: card_created_at,
                  content: card_comment,
                  contentTextMaxLines: 2,
                  imageUrls: card_resources,
                ),
              // child: Text("455"),
            ),
          ),
        );
      }
    );
  }

  Widget _buildSelectHouseCleanOrAirConditioner(BuildContext context, WidgetRef ref, PaidServiceDetailEntity detailInfo) {
    if(cleanServiceTypeId == servicesConstants.paidServicesType['houseCleaning']!['id']){
      List<PaidServiceDetailProducts>? houseCleanList = detailInfo?.products??[];
      // 室内清洁
      return houseCleanList.isNotEmpty? Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 16, right: 16,top: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const MyAssetImage(
                  Assets.serviceServiceAvatorIcon,
                  width: 15,
                  height: 17.5,
                ),
                const SizedBox(
                  width: 10,
                ),
                MyTextView(
                  S.current.service,
                  fontSize: 17,
                  isFontBold: true,
                  textColor: context.appColors.textBlack,
                ),
              ],
            ),
          ),
          ChooseHouseCleanContent(id: id, cleanServiceTypeId: cleanServiceTypeId, products: houseCleanList),
        ],
      ): SizedBox.shrink();
    }else if(cleanServiceTypeId == servicesConstants.paidServicesType['airConditioner']!['id']){
      // 空调清洁  页面中没有直接展示 选择数量的  直接在弹窗中选择了
      // return ChooseAirConditionContent(id: id, cleanServiceTypeId: cleanServiceTypeId);
    }
    return SizedBox.shrink();
  }

  Widget _buildBottomConcatInfo(
      BuildContext context,
      WidgetRef ref,
      likeButtonKey,
      {
        required PaidServiceDetailEntity detailInfo,
      }
      ) {
    final vm = ref.read(serviceCleanDetailVmProvider.notifier);

    PaidServiceDetailMerchant? merchant = detailInfo?.merchant??null;
    final contact = merchant?.contactPhone??"";

    int? likes_count = likesCount?? 0;
    bool isLiked = liked?? false;

    final _likes_count = useState<int>(likes_count!);
    final _isLiked = useState<bool>(isLiked);


    return Container(
      height: 50,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        children: [
          Container(
            width: 122,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.max,
              children: [
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.only(left:5, right: 0,top:5,bottom: 5),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      MyLikeButton(
                        key: likeButtonKey,
                        isLiked: _isLiked.value,
                        isCustomIcon: true,
                        customIconUnActiveAssets: Assets.communityCollection,
                        customIconActiveAssets: Assets.communityLikeActive,
                        customIconWidth: 20,
                        customIconHeight: 18,
                        onLike: () async {
                          Log.d('点击了like button');
                          int id = detailInfo.id!;
                          final isSuccess = await vm.handlerClickLikedBtn(context, id, true);
                          if(isSuccess!=null && isSuccess == true){
                            // 成功
                            if(_isLiked.value){
                              Log.d("取消点赞");
                              _likes_count.value--;
                              _isLiked.value = false;
                            }else {
                              Log.d("点赞");
                              _likes_count.value++;
                              _isLiked.value = true;
                            }
                          }
                        },
                      ),
                      MyTextView(
                        "${_likes_count.value}",
                        fontSize: 18,
                        textColor: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: Colors.white),
                        isFontRegular: true,
                        marginLeft: 5,
                        marginRight: 15,
                        onClick: (){
                          // 点击了like button
                          final state = likeButtonKey.currentState;
                          state?.triggerTap();
                        },
                      ),
                    ],
                  ),
                ),
                // const MyAssetImage(Assets.communityCollection, width: 18,height: 18,),
                Row(
                  children: [
                    const SizedBox(width: 4,),
                    const MyAssetImage(
                      Assets.communityPhone,
                      width: 21.5,
                      height: 18,
                    ).onTap((){
                      // 点击了打电话
                      vm.handlerClickMobile(context, contact);
                    }),
                    const SizedBox(width: 15,),
                  ],
                ),
              ],
            ).backgroundColor(DarkThemeUtil.multiColors(context, context.appColors.textPrimary, darkColor: AppColorsTheme.colorPrimary)),
          ),
          Expanded(
            child: Container(
              color: DarkThemeUtil.multiColors(context, context.appColors.redDefault, darkColor: Colors.red),
              child: Center(
                child: MyTextView(
                 S.current.book_now,
                  textColor: DarkThemeUtil.multiColors(context,context.appColors.textWhite, darkColor: Colors.white),
                  fontSize: 17,
                  isFontMedium: true,
                  textAlign: TextAlign.center,
                ),
              ),
            ).onTap((){
              vm.handlerClickBookNow(context, id: id , cleanServiceTypeId: cleanServiceTypeId,);
            }),
          ),
        ],
      ),
    );
  }
}
