import 'package:cpt_form/modules/apply/vm/apply_view_model.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/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/shatter/picker_container.dart';
import 'package:widgets/widget_export.dart';
import '../../router/page/form_page_router.dart';

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

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

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

    // 使用 useState 来持久化 TextEditingController 和 FocusNode
    final TextEditingController vehicleNumController = useTextEditingController();
    final TextEditingController iuNumController = useTextEditingController();
    final TextEditingController vehicleInfoController = useTextEditingController();
    final FocusNode vehicleNumFocusNode = useFocusNode();
    final FocusNode iuNumFocusNode = useFocusNode();
    final FocusNode vehicleInfoFocusNode = useFocusNode();

    useEffect(() {
      //赋值State的值
      Future.microtask(() {
        vehicleNumController.text = state.formContentDetail.vehicleNumber ?? "";
        iuNumController.text = state.formContentDetail.iuNumber ?? "";
        vehicleInfoController.text = state.formContentDetail.vehicleMakeModelColour ?? "";
      });

      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: [
                        //下拉选 - Type类型
                        FormRequireText(
                          text: S.current.type_of_application,
                          textColor: context.appColors.textBlack,
                          fontSize: 17,
                          fontWeight: FontWeight.w500,
                        ).marginOnly(top: 30, bottom: 16, left: 15, right: 15),

                        PickerContainer(
                          hint: S.current.choose_an_option,
                          enable: state.enableEdit,
                          content: state.formContentDetail.typeOfApplication,
                          onClick: () {
                            viewModel.pickOption(true);
                          },
                        ).marginOnly(left: 15, right: 15),

                        //下拉选 - 所有权状态
                        FormRequireText(
                          text: S.current.ownership_status,
                          textColor: context.appColors.textBlack,
                          fontSize: 17,
                          fontWeight: FontWeight.w500,
                        ).marginOnly(top: 14, bottom: 16, left: 15, right: 15),

                        PickerContainer(
                          hint: S.current.choose_an_option,
                          enable: state.enableEdit,
                          content: state.formContentDetail.ownershipStatus,
                          onClick: () {
                            viewModel.pickOption(false);
                          },
                        ).marginOnly(left: 15, right: 15),

                        //输入框 - 车牌号
                        FormRequireText(
                          text: S.current.vehicle_number,
                          textColor: context.appColors.textBlack,
                          fontSize: 17,
                          fontWeight: FontWeight.w500,
                        ).marginOnly(top: 14, bottom: 16, left: 15, right: 15),

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

                        //输入框 - IU 号
                        MyTextView(
                          S.current.iu_number,
                          fontSize: 17,
                          marginTop: 14,
                          marginLeft: 15,
                          marginRight: 15,
                          marginBottom: 16,
                          isFontMedium: true,
                          textColor: context.appColors.textBlack,
                        ),

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

                        //输入框 - 车辆信息
                        FormRequireText(
                          text: S.current.vehicle_make_model_colour,
                          textColor: context.appColors.textBlack,
                          fontSize: 17,
                          fontWeight: FontWeight.w500,
                        ).marginOnly(top: 14, bottom: 16, left: 15, right: 15),

                        // 表单
                        _buildInputLayout(
                          context,
                          "vehicle_info",
                          enable: state.enableEdit,
                          textInputType: TextInputType.text,
                          textInputAction: TextInputAction.done,
                          controller: vehicleInfoController,
                          focusNode: vehicleInfoFocusNode,
                          onSubmit: (formKey, value) {
                            vehicleInfoFocusNode.unfocus();
                          },
                        ),
                      ],
                    ),
                  ),
                ).expanded(),

                //底部按钮
                MyButton(
                  onPressed: () {
                    vehicleNumFocusNode.unfocus();
                    iuNumFocusNode.unfocus();
                    vehicleInfoFocusNode.unfocus();

                    if (state.enableEdit) {
                      String? vehicleNumber = vehicleNumController.text;
                      String? iuNumber = iuNumController.text;
                      String? vehicleMakeModelColour = vehicleInfoController.text;

                      //校验数据
                      final typeOfApplication = state.formContentDetail.typeOfApplication;
                      final ownershipStatus = state.formContentDetail.ownershipStatus;

                      if (Utils.isEmpty(typeOfApplication)) {
                        ToastEngine.show("Select Type Of Application");
                        return;
                      }

                      if (Utils.isEmpty(ownershipStatus)) {
                        ToastEngine.show("Select Ownership Status");
                        return;
                      }

                      if (Utils.isEmpty(vehicleNumber)) {
                        ToastEngine.show("Enter vehicle number");
                        return;
                      }

                      if (Utils.isEmpty(vehicleMakeModelColour)) {
                        ToastEngine.show("Enter vehicle make/model/ colour");
                        return;
                      }

                      //存入本表单数据
                      viewModel.updateFormContentDetail((content) {
                        content.vehicleNumber = vehicleNumber;
                        content.vehicleMakeModelColour = vehicleMakeModelColour;
                        content.iuNumber = iuNumber;
                      });
                    }

                    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,
      ),
    );
  }
}