import 'package:cs_resources/generated/assets.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/date_time_utils.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';
import 'package:widgets/my_text_field.dart';
import 'package:widgets/shatter/form_require_text.dart';
import 'package:widgets/shatter/picker_container.dart';

import '../../../router/page/main_page_router.dart';
import 'visitor_register_state.dart';
import 'visitor_register_view_model.dart';

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

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

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

    return Scaffold(
      appBar: MyAppBar.appBar(context, S.current.visitor_registration),
      backgroundColor: context.appColors.backgroundWhite,
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        physics: const BouncingScrollPhysics(),
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 15),
          width: double.infinity,
          child: Column(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              //全名
              FormRequireText(
                text: S.current.full_name,
                textColor: context.appColors.textBlack,
                fontSize: 17,
              ).marginOnly(top: 14.5),
              // 表单
              _buildInputLayout(
                context,
                state,
                marginTop: 16,
                "full_name",
                textInputType: TextInputType.text,
                textInputAction: TextInputAction.next,
                errorText: state.fullNameErrorText,
                onSubmit: (formKey, value) {
                  state.formData[formKey]!['focusNode'].unfocus();
                  FocusScope.of(context).requestFocus(state.formData['phone']!['focusNode']);
                },
              ),

              //移动电话
              FormRequireText(
                text: S.current.mobile_phone,
                textColor: context.appColors.textBlack,
                fontSize: 17,
              ).marginOnly(top: 14.5),
              // 表单
              _buildInputLayout(
                context,
                state,
                "phone",
                marginTop: 16,
                textInputType: TextInputType.phone,
                textInputAction: TextInputAction.next,
                errorText: state.phoneErrorText,
                onSubmit: (formKey, value) {
                  state.formData[formKey]!['focusNode'].unfocus();
                  FocusScope.of(context).requestFocus(state.formData['nric']!['focusNode']);
                },
              ),

              // 身份证
              FormRequireText(
                text: S.current.nric_fin,
                textColor: context.appColors.textBlack,
                fontSize: 17,
              ).marginOnly(top: 14.5),
              // 表单
              _buildInputLayout(
                context,
                state,
                "nric",
                marginTop: 15,
                textInputType: TextInputType.text,
                textInputAction: TextInputAction.next,
                errorText: state.nricErrorText,
                onSubmit: (formKey, value) {
                  state.formData[formKey]!['focusNode'].unfocus();
                  FocusScope.of(context).requestFocus(state.formData['plate_number']!['focusNode']);
                },
              ),

              // 车牌号
              MyTextView(
                S.current.license_plate_number,
                textColor: context.appColors.textBlack,
                fontSize: 17,
                marginTop: 14.5,
                isFontMedium: true,
              ),
              // 表单
              _buildInputLayout(
                context,
                state,
                "plate_number",
                marginTop: 15,
                textInputType: TextInputType.text,
                textInputAction: TextInputAction.next,
                onSubmit: (formKey, value) {
                  state.formData[formKey]!['focusNode'].unfocus();
                  FocusScope.of(context).requestFocus(state.formData['access_date']!['focusNode']);
                },
              ),

              // 通行时间
              FormRequireText(
                text: S.current.access_date,
                textColor: context.appColors.textBlack,
                fontSize: 17,
              ).marginOnly(top: 14.5),
              // 选择器
              PickerContainer(
                content: state.accessDate == null ? "" : DateTimeUtils.formatDate(state.accessDate, format: 'dd MMM yyyy'),
                margin: const EdgeInsets.only(top: 16),
                rightWidget:  MyAssetImage(
                  Assets.mainVisitorRegisterDate,
                  width: 21,
                  height: 20,
                  color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary,darkColor: Colors.white),
                ),
                onClick: (context){
                  viewModel.pickAccessDate();
                },
              ),

              // 备注
              MyTextView(
                S.current.notes,
                textColor: context.appColors.textBlack,
                fontSize: 17,
                marginTop: 14.5,
                isFontMedium: true,
              ),
              //大文本框
              IgnoreKeyboardDismiss(
                child: Container(
                  height: 177,
                  margin: const EdgeInsets.only(top: 16),
                  padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 15),
                  decoration: BoxDecoration(
                    color: context.appColors.authFiledBG,
                    borderRadius: const BorderRadius.all(Radius.circular(5)),
                  ),
                  child: Stack(
                    children: [
                      TextField(
                        cursorColor: context.appColors.authFiledText,
                        cursorWidth: 1.5,
                        autofocus: false,
                        enabled: true,
                        focusNode: state.formData["note"]!['focusNode'],
                        controller: state.formData["note"]!['controller'],
                        decoration: InputDecoration(
                          isDense: true,
                          isCollapsed: true,
                          border: InputBorder.none,
                          hintText: state.formData["note"]!['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();
                          viewModel.submitVisitorRegister();
                        },
                        maxLines: null,
                        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,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              MyButton(
                onPressed: viewModel.submitVisitorRegister,
                text: S.current.submit,
                textColor: Colors.white,
                backgroundColor: context.appColors.btnBgDefault,
                fontWeight: FontWeight.w500,
                type: ClickType.throttle,
                fontSize: 16,
                minHeight: 50,
                radius: 5,
              ).marginOnly(top: 25, bottom: 25),
            ],
          ),
        ),
      ),
    );
  }

  /// 输入框
  Widget _buildInputLayout(
    BuildContext context,
    VisitorRegisterState 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,
  }) {
    return IgnoreKeyboardDismiss(
      child: MyTextField(
        key,
        fillBackgroundColor: context.appColors.authFiledBG,
        state.formData[key]!['value'],
        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: 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,
      ),
    );
  }
}
