import 'package:cpt_community/modules/community/community_vm.dart';
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:widgets/ext/ex_widget.dart';
import 'package:widgets/my_appbar.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/my_button.dart';

import 'newsfeed_post_vm.dart';

@RoutePage()
class NewsfeedPostPage extends HookConsumerWidget {
  final VoidCallback? sCallback; // 成功回调函数
  final VoidCallback? fCallback; // 失败回调函数
  const NewsfeedPostPage({Key? key, this.sCallback, this.fCallback}) : super(key: key);

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.read(newsfeedPostVmProvider.notifier);

    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        S.current.create_post,
        backgroundColor: context.appColors.backgroundWhite,
      ),
      backgroundColor: DarkThemeUtil.multiColors(context, ColorUtils.string2Color("#F2F3F6"), darkColor: Colors.black),
      body: Column(
          children: [
            Expanded(
                child: SingleChildScrollView(
                    scrollDirection: Axis.vertical,
                    physics: const BouncingScrollPhysics(),
                    clipBehavior: Clip.none,
                    child: Column(
                        children: [
                          // mind textearea
                          Container(
                            margin: const EdgeInsets.only(left:15, right:15,top: 20),
                            width: double.infinity,
                            height: 200,
                            padding: const EdgeInsets.all(15),
                            decoration: BoxDecoration(
                                color: context.appColors.whiteBG,
                                borderRadius: BorderRadius.circular(5),
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.grey.withOpacity(0.2),
                                    spreadRadius:1,
                                    blurRadius: 2,
                                    offset: const Offset(0.5, 0.5), // changes position of shadow
                                  ),
                                ]
                            ),
                            child: _buildTextAreaLayout(context,ref,'mind',),
                          ),
                          Container(
                            width: double.infinity,
                            height: 200,
                            margin: const EdgeInsets.only(left:15, right:15, top: 20, bottom: 20),
                            padding: const EdgeInsets.all(15),
                            decoration: BoxDecoration(
                                color: context.appColors.whiteBG,
                                borderRadius: BorderRadius.circular(5),
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.grey.withOpacity(0.2),
                                    spreadRadius:1,
                                    blurRadius: 2,
                                    offset: const Offset(0.5, 0.5), // changes position of shadow
                                  ),
                                ]
                            ),
                            // 选择图片上传 控件
                            child: _buildImageSelectCmp(context, ref,vm),
                          ),
                        ]
                    )
                )
            ),
            // 底部 按钮
            Container(
              child: Row(
                  children: [
                    Expanded(
                      child: MyButton(
                        text: S.current.submit,
                        radius: 0,
                        minHeight: 50,
                        // backgroundColor: context.appColors.textPrimary,
                        backgroundColor: DarkThemeUtil.multiColors(context, context.appColors.textPrimary,darkColor: AppColorsTheme.color666666),
                        textColor: context.appColors.textWhite,
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                        onPressed: () {
                          vm.submitNewsfeedPost(context, sCallback: sCallback, fCallback: fCallback);
                        },
                      ),
                    ),
                  ]
              ),
            )
          ]
      ),
    );
  }

  /// 选择图片上传组件
  Widget _buildImageSelectCmp(BuildContext context, WidgetRef ref,vm,){
    final state = ref.watch(newsfeedPostVmProvider);
    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(newsfeedPostVmProvider);
    final vm = ref.read(newsfeedPostVmProvider.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,
            ),
          ),
        ),
      ]
    );
  }


  /// 单行输入框
  Widget _buildInputLayout(
      BuildContext context,
      state,
      String key,
      {
        double height = 48,
        double maxLines = 1,
        double marginTop = 0,
        bool? showRightIcon = false, //是否展示右侧的布局
        Widget? rightWidget, //右侧的布局
        TextInputType textInputType = TextInputType.text,
        String? errorText,
        bool obscureText = false,
        TextInputAction textInputAction = TextInputAction.done,
        Function? onSubmit,
      }) {
    return IgnoreKeyboardDismiss(
      child: MyTextField(
        key,
        fillBackgroundColor: context.appColors.authFiledBG,
        state.formData[key]!['value'],
        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,
        height: height,
        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,
      ),
    );
  }

}
