import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.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/rendering.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:plugin_basic/provider/app_config/app_config_service.dart';
import 'package:plugin_platform/engine/image/image_nine_grid.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/screen_util.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 'package:widgets/shatter/form_require_text.dart';
import 'package:widgets/my_text_field.dart';

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

@RoutePage()
class ServiceEvaluateCreatePage extends HookConsumerWidget {
  final int id;
  final int? cleanServiceTypeId;
  const ServiceEvaluateCreatePage({
    Key? key,
    required this.id,
    this.cleanServiceTypeId,
  }) : super(key: key);

  //启动当前页面
  static void startInstance({BuildContext? context, required int id, int? cleanServiceTypeId}) {
    if (context != null) {
      context.router.push(ServiceEvaluateCreatePageRoute(id: id, cleanServiceTypeId: cleanServiceTypeId));
    } else {
      appRouter.push(ServiceEvaluateCreatePageRoute(id:id, cleanServiceTypeId: cleanServiceTypeId));
    }
  }


  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.read(serviceEvaluateCreateVmProvider.notifier);
    final state = ref.watch(serviceEvaluateCreateVmProvider);
    // final appConfigState = ref.watch(appConfigServiceProvider)

    final _score = useState<double>(state.score?? 5.0);

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

    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        S.current.evaluate,
        backgroundColor: context.appColors.whiteBG,
        showBottomDivider:true,
      ),
      backgroundColor: DarkThemeUtil.multiColors(context, ColorUtils.string2Color('#F2F3F6'), darkColor: Colors.black)?? Colors.black,
      body: Column(
          children: [
            Expanded(
                child: SingleChildScrollView(
                    scrollDirection: Axis.vertical,
                    physics: const BouncingScrollPhysics(),
                    clipBehavior: Clip.none,
                    child: Column(
                        children: [
                          // notes
                          Container(
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    // 提示文字
                                    Container(
                                      width: double.infinity,
                                      color: context.appColors.whiteBG,
                                      child: MyTextView(
                                        S.current.submit_feedback_encourage,
                                        textColor: context.appColors.textBlack,
                                        fontSize: 15,
                                        paddingTop: 16,
                                        paddingBottom: 16,
                                        paddingLeft: 10.5,
                                        paddingRight: 10.5,
                                      ),
                                    ),
                                    // 评价分
                                    Container(
                                      width: double.infinity,
                                      padding: const EdgeInsets.only(left: 10.5, right: 10.5,top: 15,bottom: 15),
                                      margin: const EdgeInsets.only(top: 5, bottom: 0),
                                      color: context.appColors.whiteBG,
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          MyTextView(
                                            S.current.score,
                                            textColor: context.appColors.textBlack,
                                            fontSize: 17,
                                            isFontBold: true,
                                            backgroundColor: context.appColors.whiteBG,
                                            marginBottom: 10,
                                          ),
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.start,
                                            crossAxisAlignment: CrossAxisAlignment.center,
                                            children: [
                                              AnimatedRatingStars(
                                                initialRating: _score.value,
                                                onChanged: (rating) {
                                                  Log.d("rating 变化 $rating");
                                                  _score.value = rating;
                                                  vm.setScore(context, _score.value);
                                                },
                                                readOnly: false,
                                                displayRatingValue: true, // Display the rating value
                                                interactiveTooltips: true, // Allow toggling half-star state
                                                customFilledIcon: Icons.star,
                                                customHalfFilledIcon: Icons.star_half,
                                                customEmptyIcon: Icons.star_border,
                                                starSize: 30.0,
                                                animationDuration: const Duration(milliseconds: 300),
                                                animationCurve: Curves.easeInOut,
                                              ),
                                              MyTextView(
                                                "${_score.value}",
                                                textColor: context.appColors.textBlack,
                                                fontSize: 25,
                                                isFontRegular: true,
                                                backgroundColor: context.appColors.whiteBG,
                                                marginLeft: 16,
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                    // Notes
                                    Container(
                                      width: double.infinity,
                                      padding: const EdgeInsets.only(left: 10.5, right: 10.5,top: 15,bottom: 15),
                                      margin: const EdgeInsets.only(top: 5, bottom: 0),
                                      color: context.appColors.whiteBG,
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          FormRequireText(
                                            text: S.current.notes,
                                            textColor: context.appColors.textBlack,
                                            fontSize: 17,
                                            fontWeight: FontWeight.bold,
                                          ),
                                          SizedBox(height: 16,),
                                          _buildTextArea(context, ref, 'notes',),
                                        ],
                                      ),
                                    ),
                                    // upload Image
                                    Container(
                                      width: double.infinity,
                                      padding: const EdgeInsets.only(left: 10.5, right: 10.5,top: 15,bottom: 15),
                                      margin: const EdgeInsets.only(top: 5, bottom: 0),
                                      color: context.appColors.whiteBG,
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          FormRequireText(
                                            text: "${S.current.upload_image}:",
                                            textColor: context.appColors.textBlack,
                                            fontSize: 17,
                                            fontWeight: FontWeight.bold,
                                          ),
                                          MyTextView(
                                            S.current.up_3_img,
                                            fontSize: 13,
                                            isFontMedium: true,
                                            textColor: context.appColors.textDarkGray999,
                                            marginTop: 8.5,
                                          ),
                                          SizedBox(height: 16,),
                                          // 选择图片上传 控件
                                          _buildImageSelectCmp(context, ref,vm),
                                        ],
                                      ),
                                    ),
                                  ]
                              )

                          ),
                        ]
                    )
                )
            ),
            // 底部 按钮
            Container(
              child: Row(
                  children: [
                    Expanded(
                      child: MyButton(
                        text: S.current.submit,
                        radius: 0,
                        minHeight: 50,
                        backgroundColor: DarkThemeUtil.multiColors(context, context.appColors.textPrimary, darkColor: AppColorsTheme.color666666),
                        textColor: Colors.white,
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                        onPressed: () {
                          vm.handlerEvaluateSubmit(context);
                        },
                      ),
                    ),
                  ]
              ),
            )
          ]
      ),
    );
  }

  /// textarea
  Widget _buildTextArea(BuildContext context, WidgetRef ref, key){
    return Container(
      width: double.infinity,
      height: 200,
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: context.appColors.authFiledBG,
        borderRadius: BorderRadius.circular(5),
      ),
      child: _buildTextAreaLayout(
        context,
        ref,
        key,
      ),
    );
  }
  /// 选择图片上传组件
  Widget _buildImageSelectCmp(BuildContext context, WidgetRef ref,vm,){
    final state = ref.watch(serviceEvaluateCreateVmProvider);
    return ImageNineGrid(
      isSelectEnable: true,
      maxImages: 10,
      spacing: 10,
      aspectRatio: 108 / 80,
      initialImages: state.imgList,
      onImagesChanged: (list) {
        vm.setImgList(list);
      },
    );
  }

  /// 多行输入框
  Widget _buildTextAreaLayout(BuildContext context, ref, key){
    final state = ref.watch(serviceEvaluateCreateVmProvider);
    final vm = ref.read(serviceEvaluateCreateVmProvider.notifier);
    final noteCount = useState(0);

    return Stack(
        children: [
          TextField(
            cursorColor: context.appColors.authFiledText,
            cursorWidth: 1.5,
            autofocus: false,
            enabled: true,
            maxLines: null,
            focusNode: state.formData[key]!['focusNode'],
            controller: state.formData[key]!['controller'],
            decoration: InputDecoration(
              isDense: true,
              isCollapsed: true,
              border: InputBorder.none,
              hintText: state.formData[key]!['hintText'],
              hintStyle: TextStyle(
                color: context.appColors.authFiledHint,
                fontSize: 16.0,
                fontWeight: FontWeight.w500,
              ),
            ),
            style: TextStyle(
              color: context.appColors.authFiledText,
              fontSize: 16.0,
              fontWeight: FontWeight.w500,
            ),
            textInputAction: TextInputAction.done,
            onSubmitted: (value) {
              FocusScope.of(context).unfocus();
            },
            expands: true,
            onChanged: (text) {
              // 当文本改变时，更新字符数量
              vm.setNotes(context, text);
              noteCount.value = text.length;
            },
          ),
          Positioned(
            bottom: 0.0,
            right: 0.0,
            child: Text(
              S.current.characters(noteCount.value),
              style: TextStyle(
                color: context.appColors.textBlack,
                fontSize: 15.0,
              ),
            ),
          ),
        ]
    );
  }

  /// 单行输入框
  Widget _buildInputLayout(
      BuildContext context,
      WidgetRef ref,
      state,
      String key,
      {
        double marginTop = 0,
        bool? showRightIcon = false, //是否展示右侧的布局
        Widget? rightWidget, //右侧的布局
        TextInputType textInputType = TextInputType.text,
        String? errorText,
        bool obscureText = false,
        bool enable = true,
        TextInputAction textInputAction = TextInputAction.done,
        Function? onSubmit,
      }) {
    // final state = ref.watch(garagesalePostVmProvider);
    return IgnoreKeyboardDismiss(
      child: MyTextField(
        key,
        state.formData[key]!['value'],
        fillBackgroundColor: context.appColors.authFiledBG,
        hintText: state.formData[key]!['hintText'],
        hintStyle: TextStyle(
          color: context.appColors.authFiledHint,
          fontSize: 16.0,
          fontWeight: FontWeight.w500,
        ),
        controller: state.formData[key]!['controller'],
        focusNode: state.formData[key]!['focusNode'],
        margin: EdgeInsets.only(top: marginTop),
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 3),
        showDivider: false,
        style: TextStyle(
          color: context.appColors.authFiledText,
          fontSize: 16.0,
          fontWeight: FontWeight.w500,
        ),
        inputType: textInputType,
        textInputAction: textInputAction,
        onSubmit: onSubmit,
        cursorColor: context.appColors.authFiledText,
        obscureText: obscureText,
        errorText: errorText,
        showLeftIcon: true,
        showRightIcon: showRightIcon,
        rightWidget: rightWidget,
      ),
    );
  }
} 