import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/dropdown/country_dropdown_widget.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:provider/provider.dart';

class FamilyFileAddWidget extends StatefulWidget {
  final Function()? onVerificationPress;
  final String message;

  const FamilyFileAddWidget(this.onVerificationPress, this.message, {super.key});

  @override
  State<FamilyFileAddWidget> createState() => _FamilyFileAddWidgetState();
}

class _FamilyFileAddWidgetState extends State<FamilyFileAddWidget> {
  late AuthenticationViewModel _authVm;

  @override
  void initState() {
    super.initState();

    // Get ViewModel reference early
    _authVm = getIt.get<AuthenticationViewModel>();

    // Clear errors when family file add widget is opened
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _authVm.clearNationalIdError();
      _authVm.clearPhoneNumberError();
    });
  }

  @override
  void dispose() {
    // Clear errors when family file add widget is closed
    // Use post frame callback to avoid calling notifyListeners during dispose
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _authVm.clearNationalIdError();
      _authVm.clearPhoneNumberError();
    });

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Use the stored reference instead of getting it here
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        widget.message.toText16(color: AppColors.textColor, isBold: true),
        SizedBox(height: 20.h),
        Selector<AuthenticationViewModel, bool>(
          selector: (_, model) => model.hasIdAndPhoneError,
          builder: (context, hasError, child) {
            return Container(
              decoration: BoxDecoration(
                color: AppColors.whiteColor,
                borderRadius: BorderRadius.circular(24),
                border: Border.all(
                  color: hasError
                      ? AppColors.primaryRedBorderColor
                      : Colors.transparent,
                  width: 1,
                ),
              ),
              padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 8.h),
              child: Column(
            children: [
              CustomCountryDropdown(
                countryList: CountryEnum.values.where((c) => c != CountryEnum.others).toList(),
                onCountryChange: _authVm.onCountryChange,
              ).paddingOnly(top: 8.h, bottom: 16.h),
              Divider(height: 1.h, color: AppColors.spacerLineColor),
              TextInputWidget(
                labelText: LocaleKeys.nationalIdNumber.tr(),
                hintText: "xxxxxxxxx",
                controller: _authVm.nationalIdController,
                isEnable: true,
                prefix: null,
                isAllowRadius: true,
                isBorderAllowed: false,
                isAllowLeadingIcon: true,
                autoFocus: false,
                keyboardType: TextInputType.number,
                fontFamily: "Poppins",
                padding: EdgeInsets.symmetric(vertical: 8.h),
                leadingIcon: AppAssets.student_card,
                hasError: false,  // Don't show individual field border
                errorMessage: _authVm.nationalIdError,  // Show error message if exists
                onChange: (value) {
                  // Clear error when user starts typing
                  _authVm.clearNationalIdError();
                },
              ).paddingOnly(top: 8.h, bottom: 8.h),
              Divider(height: 1.h, color: AppColors.spacerLineColor),
              Selector<AuthenticationViewModel, String>(
                selector: (_, model) => model.selectedCountrySignup.countryCode,
                builder: (context, countryCode, child) {
                  return TextInputWidget(
                    labelText: LocaleKeys.phoneNumber.tr(),
                    hintText: "",
                    controller: _authVm.phoneNumberController,
                    isEnable: true,
                    prefix: countryCode,
                    isAllowRadius: true,
                    isBorderAllowed: false,
                    isAllowLeadingIcon: true,
                    autoFocus: false,
                    keyboardType: TextInputType.number,
                    fontFamily: "Poppins",
                    padding: EdgeInsets.symmetric(vertical: 8.h),
                    leadingIcon: AppAssets.smart_phone,
                    hasError: false,  // Don't show individual field border
                    errorMessage: _authVm.phoneNumberError,  // Show error message if exists
                    onChange: (value) {
                      // Clear error when user starts typing
                      _authVm.clearPhoneNumberError();
                    },
                  ).paddingOnly(top: 8.h, bottom: 4.h);
                },
              ),
            ],
          ),
        );
          },
        ),
        SizedBox(height: 20.h),
        CustomButton(
            text: LocaleKeys.add.tr(context: context),
            onPressed: () {
              // Unfocus all text fields and dismiss keyboard
              FocusManager.instance.primaryFocus?.unfocus();

              // Use ViewModel validation method
              if (_authVm.validateIdAndPhone()) {
                // _authVm.addFamilyMember(otpTypeEnum: OTPTypeEnum.sms, isExcludedUser: true);
                if (widget.onVerificationPress != null) {
                  widget.onVerificationPress!();
                }
              }
            },
            icon: AppAssets.add_icon,
            height: 56.h,
            isBold: true),
        SizedBox(height: 20.h),
      ],
    );
  }
}
