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/toast/toast_engine.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_text_field.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/shatter/form_require_text.dart';
import 'package:widgets/widget_export.dart';
import '../../router/page/form_page_router.dart';
import 'vm/apply_view_model.dart';

@RoutePage()
class RenovationCompanyPage extends HookConsumerWidget {
  const RenovationCompanyPage({Key? key}) : super(key: key);

  //启动当前页面
  static void startInstance({BuildContext? context}) {
    if (context != null) {
      context.router.push(const RenovationCompanyPageRoute());
    } else {
      appRouter.push(const RenovationCompanyPageRoute());
    }
  }

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

    // 使用 useState 来持久化 TextEditingController 和 FocusNode
    final companyController = useTextEditingController();
    final contactController = useTextEditingController();
    final phoneController = useTextEditingController();
    final addressController = useTextEditingController();

    final companyFocusNode = useFocusNode();
    final contactFocusNode = useFocusNode();
    final phoneFocusNode = useFocusNode();
    final addressFocusNode = useFocusNode();

    useEffect(() {
      //赋值State的值
      Future.microtask(() {
        companyController.text = state.formContentDetail.renovationCompany ?? "";
        contactController.text = state.formContentDetail.personInCharge ?? "";
        phoneController.text = state.formContentDetail.mobileNumber ?? "";
        addressController.text = state.formContentDetail.companyAddress ?? "";
      });

      return () {};
    }, []);

    return WillPopScope(
        child: Scaffold(
            appBar: MyAppBar.appBar(context, state.detailPage?['title']),
            backgroundColor: context.appColors.backgroundWhite,
            body: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  physics: const BouncingScrollPhysics(),
                  child: Container(
                    width: double.infinity,
                    child: Column(
                      mainAxisSize: MainAxisSize.max,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        //输入框 - 装修公司
                        FormRequireText(
                          text: S.current.renovation_company,
                          textColor: context.appColors.textBlack,
                          fontSize: 17,
                          fontWeight: FontWeight.w500,
                        ).marginOnly(top: 14, bottom: 16, left: 15, right: 15),

                        // 表单
                        _buildInputLayout(
                          context,
                          "company",
                          enable: state.enableEdit,
                          textInputType: TextInputType.text,
                          textInputAction: TextInputAction.next,
                          controller: companyController,
                          focusNode: companyFocusNode,
                          onSubmit: (formKey, value) {
                            companyFocusNode.unfocus();
                            FocusScope.of(context).requestFocus(contactFocusNode);
                          },
                        ),

                        //输入框 - 联系人
                        FormRequireText(
                          text: S.current.person_in_charge,
                          textColor: context.appColors.textBlack,
                          fontSize: 17,
                          fontWeight: FontWeight.w500,
                        ).marginOnly(top: 14, bottom: 16, left: 15, right: 15),

                        // 表单
                        _buildInputLayout(
                          context,
                          "contact",
                          enable: state.enableEdit,
                          textInputType: TextInputType.text,
                          textInputAction: TextInputAction.next,
                          controller: contactController,
                          focusNode: contactFocusNode,
                          onSubmit: (formKey, value) {
                            contactFocusNode.unfocus();
                            FocusScope.of(context).requestFocus(phoneFocusNode);
                          },
                        ),

                        //输入框 - 联系电话
                        FormRequireText(
                          text: S.current.mobile_phone,
                          textColor: context.appColors.textBlack,
                          fontSize: 17,
                          fontWeight: FontWeight.w500,
                        ).marginOnly(top: 14, bottom: 16, left: 15, right: 15),

                        // 表单
                        _buildInputLayout(
                          context,
                          "phone",
                          enable: state.enableEdit,
                          textInputType: TextInputType.phone,
                          textInputAction: TextInputAction.next,
                          controller: phoneController,
                          focusNode: phoneFocusNode,
                          onSubmit: (formKey, value) {
                            phoneFocusNode.unfocus();
                            FocusScope.of(context).requestFocus(addressFocusNode);
                          },
                        ),

                        //输入框 - 公司地址
                        MyTextView(
                          S.current.company_address,
                          fontSize: 17,
                          marginTop: 14,
                          marginBottom: 16,
                          marginLeft: 15,
                          marginRight: 15,
                          isFontMedium: true,
                          textColor: context.appColors.textBlack,
                        ),

                        //文本框
                        IgnoreKeyboardDismiss(
                          child: Container(
                            height: 160,
                            margin: const EdgeInsets.symmetric(horizontal: 15),
                            padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 15),
                            decoration: BoxDecoration(
                              color: context.appColors.authFiledBG,
                              borderRadius: const BorderRadius.all(Radius.circular(5)),
                            ),
                            child: TextField(
                              cursorColor: context.appColors.authFiledText,
                              cursorWidth: 1.5,
                              autofocus: false,
                              enabled: state.enableEdit,
                              focusNode: addressFocusNode,
                              controller: addressController,
                              decoration: InputDecoration(
                                isDense: true,
                                isCollapsed: true,
                                border: InputBorder.none,
                                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();
                              },
                              maxLines: null,
                              expands: true,
                              onChanged: (text) {
                                // 当文本改变时
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ).expanded(),

                //底部按钮
                MyButton(
                  onPressed: () {
                    companyFocusNode.unfocus();
                    contactFocusNode.unfocus();
                    phoneFocusNode.unfocus();
                    addressFocusNode.unfocus();

                    if (state.enableEdit) {
                      String? renovationCompany = companyController.text;
                      String? personInCharge = contactController.text;
                      String? mobileNumber = phoneController.text;
                      String? companyAddress = addressController.text;

                      if (Utils.isEmpty(renovationCompany)) {
                        ToastEngine.show("Enter Renovation Company");
                        return;
                      }

                      if (Utils.isEmpty(personInCharge)) {
                        ToastEngine.show("Enter Person In Charge");
                        return;
                      }

                      if (Utils.isEmpty(mobileNumber)) {
                        ToastEngine.show("Enter Mobile Number");
                        return;
                      }

                      //存入本表单数据
                      viewModel.updateFormContentDetail((content) {
                        content.renovationCompany = renovationCompany;
                        content.personInCharge = personInCharge;
                        content.mobileNumber = mobileNumber;
                        content.companyAddress = companyAddress;
                      });
                    }

                    viewModel.gotoNextPage();
                  },
                  text: S.current.next,
                  textColor: Colors.white,
                  backgroundColor: context.appColors.btnBgDefault,
                  fontWeight: FontWeight.w500,
                  type: ClickType.throttle,
                  fontSize: 16,
                  minHeight: 50,
                  radius: 0,
                ),
              ],
            )),
        onWillPop: () async {
          viewModel.handlePopAction();
          return true;
        });
  }

  Widget _buildInputLayout(
    BuildContext context,
    String key, {
    double marginTop = 0,
    bool? showRightIcon = false, //是否展示右侧的布局
    Widget? rightWidget, //右侧的布局
    TextInputType textInputType = TextInputType.text,
    String? errorText,
    bool obscureText = false,
    required TextEditingController controller,
    required FocusNode focusNode,
    bool enable = true,
    TextInputAction textInputAction = TextInputAction.done,
    Function? onSubmit,
  }) {
    return IgnoreKeyboardDismiss(
      child: MyTextField(
        key,
        fillBackgroundColor: context.appColors.authFiledBG,
        "",
        hintStyle: TextStyle(
          color: context.appColors.authFiledHint,
          fontSize: 16.0,
          fontWeight: FontWeight.w500,
        ),
        controller: controller,
        focusNode: focusNode,
        margin: EdgeInsets.only(top: marginTop, left: 15, right: 15),
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 3),
        showDivider: false,
        height: 44,
        enabled: enable,
        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,
      ),
    );
  }
}
