import 'package:cpt_services/modules/services/service_repair_detail/service_repair_detail_state.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:domain/entity/service_repair_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/richText_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_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 'service_repair_detail_vm.dart';

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

@RoutePage()
class ServiceRepairDetailPage extends HookConsumerWidget {
  final int id;
  final int? cleanServiceTypeId;

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(serviceRepairDetailVmProvider);
    final vm = ref.read(serviceRepairDetailVmProvider.notifier);
    final String pageTitle = 'Repair Details';

    ServiceRepairDetailEntity? detailInfo =
        (state.datas ?? {}) as ServiceRepairDetailEntity?;

    // String contactType =  detailInfo?['contact']??'';

    String description = '';

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

    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        pageTitle,
        backgroundColor: context.appColors.backgroundWhite,
      ),
      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 _buildContentBox(
                            context, ref, detailInfo, state, vm);
                      }, childCount: 1),
                    )
                  ],
                ),
              ]),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildContentBox(
      BuildContext context,
      WidgetRef ref,
      ServiceRepairDetailEntity? detailInfo,
      ServiceRepairDetailState state,
      ServiceRepairDetailVm vm) {
    final String title = detailInfo?.name??'';
    final description =  RichtextUtils.getHandleResult(detailInfo?.description??'');

    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          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: score,
                    //       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(
                    //       "${score}",
                    //       textColor: context.appColors.textBlack,
                    //       fontSize: 16,
                    //       isFontMedium: true,
                    //       marginLeft: 15,
                    //     ),
                    //   ],
                    // ),
                    detailInfo?.name != ''
                        ? MyTextView(
                            detailInfo?.merchant.name ?? '',
                            textColor: context.appColors.textDarkGray999,
                            fontSize: 12,
                            isFontRegular: true,
                            marginTop: 10,
                            marginBottom: 5,
                          )
                        : Container(),
                  ],
                ),
              ),
            ],
          ),
          // profile信息
          // Container(
          //   width: double.infinity,
          //   margin: const EdgeInsets.only(left: 0, right: 0, top: 5, bottom: 0),
          //   padding: const EdgeInsets.only(left: 10, right: 10, top: 18.5, bottom: 18.5),
          //   decoration: BoxDecoration(
          //     color: context.appColors.whiteBG,
          //   ),
          //   child: _buildOrderProfile(context, state, vm),
          // ),
          // quote 按钮
          Container(
              width: double.infinity,
              padding: const EdgeInsets.only(
                  left: 16, right: 16, top: 20, bottom: 20),
              color: Colors.transparent,
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Center(
                      //  Get A Quote
                      child: MyButton(
                        text: S.current.get_a_quote,
                        textColor: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: Colors.white),
                        backgroundColor: DarkThemeUtil.multiColors(context, context.appColors.textPrimary, darkColor: AppColorsTheme.color666666),
                        fontSize: 15,
                        minWidth: 310,
                        minHeight: 44.5,
                        fontWeight: FontWeight.w400,
                        onPressed: () {
                          vm.handlerGetQuote(context, id);
                        },
                      ),
                    ),
                    Center(
                      child: MyTextView(
                        S.current.merchant_contact_phone,
                        textColor: context.appColors.textBlack,
                        fontSize: 14,
                        isFontRegular: true,
                        marginTop: 17,
                        // boxWidth: 330,
                        marginLeft: 20,
                        marginRight: 20,
                        textAlign: TextAlign.center,
                      ),
                    )
                  ])),
          // 介绍图
          Padding(
              padding: const EdgeInsets.only(left: 16, right: 16, top: 16),
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children:
                  [
                    // description
                    Html(data: description),
                  ]
                  // List.generate(2, (index) {
                  //   // 创建一个映射来关联字符串和资源
                  //   final Map<String, String> assetMap = {
                  //     'serviceDetail01': Assets.serviceRepairDetail01,
                  //     'serviceDetail02': Assets.serviceRepairDetail02,
                  //   };
                  //   String curDetailStr = 'serviceDetail0${(index + 1)}';
                  //   Log.d("curDetailStr   $curDetailStr");
                  //   return MyAssetImage(
                  //     assetMap[curDetailStr]!,
                  //     width: SizeConfig().screenWidth,
                  //     fit: BoxFit.cover,
                  //   );
                  // }).toList(),
              ),
          ),
        ],
      ),
    ]);
  }

  Widget _buildOrderProfile(
    BuildContext context,
    ServiceRepairDetailState state,
    ServiceRepairDetailVm vm,
  ) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const MyAssetImage(
              Assets.serviceLocationIcon,
              width: 15,
              height: 17.5,
            ),
            const SizedBox(
              width: 10,
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                MyTextView(
                  '705 Qiming Huijin Building',
                  fontSize: 17,
                  isFontBold: true,
                  textColor: context.appColors.textBlack,
                  marginBottom: 5,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    MyTextView(
                      'Sundy',
                      fontSize: 14,
                      textColor: context.appColors.textDarkGray999,
                      isFontRegular: true,
                    ),
                    MyTextView(
                      '+6588991122',
                      fontSize: 14,
                      textColor: context.appColors.textDarkGray999,
                      isFontRegular: true,
                      marginLeft: 10,
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ],
    );
  }
}
