import 'package:cpt_community/modules/garage/garagesale_detail/garagesale_detail_vm.dart';
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/garage_sale_rent_detail_entity.dart';
import 'package:domain/entity/garage_sale_rent_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';

@RoutePage()
class GaragesaleDetailPage extends HookConsumerWidget {
  final int id;
  final String type;  // forSale  forRent  mineForSale  mineForRent

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


  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(garagesaleDetailVmProvider);
    final vm = ref.read(garagesaleDetailVmProvider.notifier);
    final String pageTitle = (type == 'forSale' || type == 'mineForSale') ? S.current.for_sale :S.current.for_rent;
    GlobalKey _likeButtonKey = GlobalKey<MyLikeButtonState>();

    GarageSaleRentDetailEntity? detailInfo = state.datas?? null;
    String title =  detailInfo?.title?? '';
    int price =  detailInfo?.price?? 0;

    String contactType =  detailInfo?.contact??'';

    String description = '';

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

    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        pageTitle,
        backgroundColor: context.appColors.backgroundWhite,
        actions: [
          type=='mineForSale'||type=='mineForRent'?Center(
            child: MyTextView(
              S.current.delete,
              textColor: DarkThemeUtil.multiColors(context, context.appColors.redDefault,darkColor: Colors.redAccent),
              fontSize: 16,
              isFontMedium: true,
              marginRight: 20,
            ).onTap((){
              vm.deleteMyGarageData(context, id!);
            }),
          ): SizedBox.shrink()
        ],
      ),
      backgroundColor: context.appColors.backgroundDefault,
      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: Visibility(
                      visible: vm.isContactWhatsApp(contactType),
                      child: _buildWhatsApp(context, ref,
                        title:title,
                        price:price,
                        contactType:contactType,
                        description:description,
                      ),
                    ),
                  ),
                ]
              ),
            ),
          ),
          // 底部联系信息
          Visibility(
            visible: state.loadingState == LoadState.State_Success,
            child: detailInfo !=null ? _buildBottomConcatInfo(context, ref, _likeButtonKey,
              title:title,
              price:price,
              contactType:contactType,
              description:description,
              detailInfo:detailInfo,
            ): Container(),
          )
        ],
      ),
    );
  }

  Widget _buildWhatsApp(BuildContext context, WidgetRef ref, {required String title, required int price, required String contactType, required String description}) {
    final vm = ref.read(garagesaleDetailVmProvider.notifier);
    return Positioned(
      right: 15.5,
      bottom: 42,
      child: InkWell(
        onTap: () {
          // 点击了whatsapp
          vm.handlerClickWhatsapp(context, contactType, title, price);
        },
        child: const MyAssetImage(Assets.communityWhatsAPP, width: 57,height: 57,),
      ),
    );
  }

  Widget _buildContentBox(BuildContext context, WidgetRef ref, GarageSaleRentDetailEntity detailInfo) {
    List<String> resources = detailInfo.resources??[];
    String goods_img = resources[0]??'';
    String title =  detailInfo.title??'';
    int price = detailInfo.price??0;
    String contactType =  '';
    String description = detailInfo.description??'';
    CarouselSliderController buttonCarouselController = CarouselSliderController();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 图片
        SizedBox(
          width: SizeConfig().screenWidth,
          height: 173.5,
          child: CarouselSlider(
            // items: [MyLoadImage(goods_img)] ,
            items: resources.map((resource) => MyLoadImage(
              resource,
              fit: BoxFit.cover, // 确保图片覆盖整个区域
              width: SizeConfig().screenWidth, // 确保图片宽度与屏幕宽度一致
              height: 173.5, // 确保图片高度与 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: title.isNotEmpty? MyTextView( title, fontSize: 18, isFontMedium: true, textColor: context.appColors.textBlack,):const SizedBox.shrink(),
            ),
            // 价格
            Padding(
              padding: const EdgeInsets.only(left: 16, right: 16, top: 10),
              child: price!=null? MyTextView( '$price', fontSize: 24, isFontMedium: true, textColor: context.appColors.textBlack,):const SizedBox.shrink(),
            ),
           //  内容
            Padding(
              padding: const EdgeInsets.only(left: 16, right: 16, top: 16),
              child: description.isNotEmpty? MyTextView( description, fontSize: 17, isFontRegular: true, textColor: context.appColors.textBlack,):const SizedBox.shrink(),
            ),
          ],
        ),

      ]
    );
  }

  Widget _buildBottomConcatInfo(
      BuildContext context,
      WidgetRef ref,
      likeButtonKey,
      {
        required String title,
        required int price,
        required String contactType,
        required String description,
        required GarageSaleRentDetailEntity detailInfo,
      }
      ) {
    final vm = ref.read(garagesaleDetailVmProvider.notifier);

    GarageSaleRentDetailAccount  account = detailInfo.account?? GarageSaleRentDetailAccount();

    String publisher =  account.name??'-';
    String publisherAvatar = account.avatar??'-';

    String contactType =  detailInfo.contact??'';
    String publisherTime =  detailInfo.createdAt??'-';
    int? likes_count =  detailInfo.likesCount??0;
    final _likes_count = useState<int>(likes_count!);
    final _isLiked = useState<bool>(false);
    return Container(
      height: 50,
      color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white.withOpacity(0.1)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox.fromSize(size: const Size(15, 0)),
                MyLoadImage(
                  publisherAvatar,
                  width: 29,
                  height: 29,
                  isCircle: true,
                ),
                SizedBox.fromSize(size: const Size(10, 0)),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    MyTextView(publisher, fontSize:12, textColor: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: Colors.white), isFontMedium: true,),
                    MyTextView(publisherTime, fontSize:10, textColor: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: Colors.white), isFontRegular: true, marginTop: 4,)
                  ],
                ),
              ],
            ),
          ),
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.only(left:5, right: 0,top:5,bottom: 5),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      MyLikeButton(
                        key: likeButtonKey,
                        isLiked: _isLiked.value,
                        isCustomIcon: true,
                        customIconUnActiveAssets: Assets.communityCollection,
                        customIconActiveAssets: Assets.communityLikeActive,
                        // customIconWidth: 18,
                        // customIconHeight: 18,
                        onLike: () async {
                          Log.d('点击了like button');
                          int id = detailInfo!.id as int;
                          final isSuccess = await vm.handlerClickCollection(context, id, true);
                          if(isSuccess!=null && isSuccess){
                            // 成功
                            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: Colors.white,
                        isFontRegular: true,
                        marginLeft: 5,
                        marginRight: 15,
                        onClick: (){
                          final state = likeButtonKey.currentState;
                          state?.triggerTap();
                        },
                      ),
                    ],
                  ),
                ),
                // const MyAssetImage(Assets.communityCollection, width: 18,height: 18,),
                // 如果从我的post 页面进入的 则电话处固定显示 编辑的入口图标
                if(type == 'mineForSale' ||  type=='mineForRent')
                  Row(
                    children: [
                      const SizedBox(width: 4,),
                      const MyAssetImage(
                        Assets.communityEdit,
                        width: 20.5,
                        height: 20,
                      ).onTap((){
                        // 进入到 编辑页面
                        vm.goToEditPage(context, type, detailInfo);
                      }),
                      const SizedBox(width: 15,),
                    ],
                  )
                else
                  // 如果不是从我的post 页面进入的则电话处显示 拨打电话的入口图标
                  Visibility(
                    visible: vm.isContactMobile(contactType),
                    child:  Row(
                      children: [
                        const SizedBox(width: 4,),
                        const MyAssetImage(
                          Assets.communityPhone,
                          width: 21.5,
                          height: 18,
                        ).onTap((){
                          vm.handlerClickMobile(context, contactType);
                        }),
                        const SizedBox(width: 15,),
                      ],
                    ),
                  )
              ],
            ),
          ),
        ],
      ),
    );
  }
}
