import 'package:cpt_community/router/page/community_page_router.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.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_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/log_utils.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_text_field.dart';
import 'package:widgets/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';
import 'package:widgets/shatter/picker_container.dart';
import 'package:widgets/shatter/form_require_text.dart';
import 'package:widgets/ext/ex_widget.dart';


import '../../community/community_vm.dart';
import 'garagesale_post_state.dart';
import 'garagesale_post_vm.dart';

@RoutePage()
class GaragesalePostPage extends HookConsumerWidget {
  int type = 1;  // 类型(1=Sale,2=Rent, 3=mineForSale 4=mineForRent)
  final VoidCallback? sCallback; // 成功回调函数
  final VoidCallback? fCallback; // 失败回调函数
  GaragesalePostPage({Key? key, required this.type, this.sCallback, this.fCallback}) : super(key: key);

  //启动当前页面
  static void startInstance({BuildContext? context, int type = 1, VoidCallback? sCallback, VoidCallback? fCallback}) {
    if (context != null) {
      context.router.push(GaragesalePostPageRoute(type:type, sCallback: sCallback, fCallback: fCallback));
    } else {
      appRouter.push(GaragesalePostPageRoute(type:type, sCallback: sCallback, fCallback: fCallback));
    }
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.watch(garagesalePostVmProvider.notifier);
    final state = ref.watch(garagesalePostVmProvider);

    useEffect((){
      WidgetsBinding.instance.addPostFrameCallback((_) {
        vm.initData(
            type:type
        );
      });
      return () => (){
      };
    },[]);
    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        (type==1 || type==2) ? S.current.post_new_item : S.current.edit,
        backgroundColor: context.appColors.backgroundWhite,
      ),
      backgroundColor: DarkThemeUtil.multiColors(context, ColorUtils.string2Color("#ffffff"), darkColor: Colors.black),
      body: Column(
          children: [
            Expanded(
                child: SingleChildScrollView(
                    scrollDirection: Axis.vertical,
                    physics: const BouncingScrollPhysics(),
                    clipBehavior: Clip.none,
                    child: Column(
                        children: [
                          // sale 选择
                          Container(
                            margin: const EdgeInsets.only(left:15, right:15, top: 5),
                            child: _buildSaleInputSelectCmp(context, ref),
                          ),
                          // category 选择
                          Container(
                            margin: const EdgeInsets.only(left:15, right:15, top: 5),
                            child: _buildCategoryInputSelectCmp(context, ref),
                          ),
                          // title
                          Container(
                              margin: const EdgeInsets.only(left:15, right:15, top: 15),
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    FormRequireText(
                                      text: S.current.title,
                                      textColor: context.appColors.textBlack,
                                      fontSize: 17,
                                    ).marginOnly(bottom: 14.5),
                                    _buildInputLayout(
                                      context,
                                      ref,
                                      state,
                                      'title',
                                      textInputType: TextInputType.text,
                                      textInputAction: TextInputAction.next,
                                      errorText: state.titleErrorText,
                                      onSubmit: (formKey, value) {
                                        state!.formData[formKey]!['focusNode'].unfocus();
                                        FocusScope.of(context).requestFocus(state.formData['contactInfo']!['focusNode']);
                                      },
                                    ),
                                  ]
                              )
                          ),
                          // contact information
                          Container(
                              margin: const EdgeInsets.only(left:15, right:15, top: 15),
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    FormRequireText(
                                      text: S.current.contact_information,
                                      textColor: context.appColors.textBlack,
                                      fontSize: 17,
                                    ).marginOnly(bottom: 14.5),
                                    Row(
                                      mainAxisSize: MainAxisSize.max,
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      children: [
                                        SizedBox(
                                          width: 205,
                                          child: _buildContactTypeSelectCmp(context, ref),
                                        ),
                                        const SizedBox(width: 15),
                                        Expanded(
                                          child: _buildInputLayout(
                                            context,
                                            ref,
                                            state,
                                            'contactInfo',
                                            textInputType: TextInputType.text,
                                            textInputAction: TextInputAction.next,
                                            errorText: state.contactInfoErrorText,
                                            onSubmit: (formKey, value) {
                                              state!.formData[formKey]!['focusNode'].unfocus();
                                              FocusScope.of(context).requestFocus(state.formData['price']!['focusNode']);
                                            },
                                          ),
                                        ),
                                      ],
                                    ),
                                  ]
                              )
                          ),
                          // price
                          Container(
                              margin: const EdgeInsets.only(left:15, right:15, top: 15),
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    FormRequireText(
                                      text: "${S.current.price}(\$)",
                                      textColor: context.appColors.textBlack,
                                      fontSize: 17,
                                    ).marginOnly(bottom: 14.5),
                                    _buildInputLayout(
                                      context,
                                      ref,
                                      state,
                                      'price',
                                      textInputType: TextInputType.text,
                                      textInputAction: TextInputAction.next,
                                      errorText: state.priceErrorText,
                                      onSubmit: (formKey, value) {
                                        state!.formData[formKey]!['focusNode'].unfocus();
                                        FocusScope.of(context).requestFocus(state.formData['description']!['focusNode']);
                                      },
                                    ),
                                  ]
                              )
                          ),
                          // description
                          Container(
                            margin: const EdgeInsets.only(left:15, right:15,top: 15),
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  FormRequireText(
                                    text: S.current.description,
                                    textColor: context.appColors.textBlack,
                                    fontSize: 17,
                                  ).marginOnly(bottom: 14.5),
                                  _buildTextArea(context, ref, 'description',),
                                ]
                            )

                          ),
                          Container(
                            width: double.infinity,
                            height: 200,
                            color: DarkThemeUtil.multiColors(context, Colors.white,darkColor: Colors.black),
                            margin: const EdgeInsets.only(left:15, right:15, top: 15, bottom: 20),
                            // 选择图片上传 控件
                            child: _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: () {
                          // Navigator.pop(context);
                          vm.submitGaragesalePost(context, sCallback: sCallback, fCallback: fCallback);
                          // final communitVm = ref.read(communityVmProvider.notifier);
                          // communitVm.getCurrentPageViewVm(null).initPageData();
                          // Navigator.pop(context);
                        },
                      ),
                    ),
                  ]
              ),
            )
          ]
      ),
    );
  }

  /// textarea
  Widget _buildTextArea(BuildContext context, WidgetRef ref, key){
    final state = ref.watch(garagesalePostVmProvider);
    final vm = ref.read(garagesalePostVmProvider.notifier);

    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(garagesalePostVmProvider);
    // Log.d("打印当前的state.imgList ${state.imgList}");
    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(garagesalePostVmProvider);
    final vm = ref.read(garagesalePostVmProvider.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) {
              // 当文本改变时，更新字符数量
              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,
              ),
            ),
          ),
        ]
    );
  }

  /// contact Information 的select 选择
  Widget _buildContactTypeSelectCmp(BuildContext context, WidgetRef ref, ){
    final vm = ref.read(garagesalePostVmProvider.notifier);
    final state = ref.watch(garagesalePostVmProvider);
    return PickerContainer(
      content: state.contactTypeSelectedOption ?? "",
      hint: S.current.choose_category,
      onClick: (context){
        vm.pickContactTypeCallback();
      },
    );
  }

  /// sale 选择
  Widget _buildSaleInputSelectCmp(BuildContext context, WidgetRef ref, ){
    final vm = ref.read(garagesalePostVmProvider.notifier);
    final state = ref.watch(garagesalePostVmProvider);
    return PickerContainer(
      content: state.saleSelectedOption ?? "",
      hint: S.current.choose_category,
      margin: const EdgeInsets.only(top: 16),
      onClick: (context){
        vm.pickSaleCallback();
      },
    );
  }

  /// category 选择
  Widget _buildCategoryInputSelectCmp(BuildContext context, WidgetRef ref, ){
    final vm = ref.read(garagesalePostVmProvider.notifier);
    final state = ref.watch(garagesalePostVmProvider);
    return PickerContainer(
      content: state.categorySelectedOption ?? "",
      hint: S.current.choose_category,
      margin: const EdgeInsets.only(top: 16),
      onClick: (context){
        vm.pickCategoryCallback();
      },
    );
  }

  /// 单行输入框
  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,
      ),
    );
  }
}
