import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/core/utils/validation_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/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/e_referral/e_referral_form_manager.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:provider/provider.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart';
import 'package:hmg_patient_app_new/widgets/dropdown/dropdown_widget.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';

class RequesterFormStep extends StatefulWidget {
  const RequesterFormStep({super.key});

  @override
  State<RequesterFormStep> createState() => RequesterFormStepState();
}

class RequesterFormStepState extends State<RequesterFormStep> {
  late TextEditingController _nameController;
  late TextEditingController _phoneController;
  late TextEditingController _otherNameController;

  late FocusNode _nameFocusNode;
  late FocusNode _phoneFocusNode;
  late FocusNode _otherNameFocusNode;

  late ReferralFormManager _formManager;

  @override
  void initState() {
    super.initState();
    _formManager = context.read<ReferralFormManager>();

    _nameController = TextEditingController();
    _phoneController = TextEditingController();
    _otherNameController = TextEditingController();

    _nameFocusNode = FocusNode();
    _phoneFocusNode = FocusNode();
    _otherNameFocusNode = FocusNode();

    // Initialize controllers with current values
    _nameController.text = _formManager.formData.requesterName ?? '';
    _phoneController.text = _formManager.formData.requesterPhone ?? '';
    _otherNameController.text = _formManager.formData.otherRelationshipName ?? '';

    // Auto-focus the name field when the step loads
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _nameFocusNode.requestFocus();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ReferralFormManager>(
      builder: (context, formManager, child) {
        return Padding(
          padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 0.0),
          child: ListView(
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            physics: const BouncingScrollPhysics(),
            children: [
              // const SizedBox(height: 12),
              _buildSectionTitle(LocaleKeys.referralRequesterInformation.tr(context: context)),
              const SizedBox(height: 12),
              _buildNameField(formManager),
              // _buildPhoneField(formManager),
              _buildRelationshipField(context, formManager),
              if (_showOtherNameField(formManager)) _buildOtherNameField(formManager),
            ],
          ),
        );
      },
    );
  }

  Widget _buildSectionTitle(String title) {
    return Text(
        title,
        style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 16)
    ).paddingSymmetrical(4, 0);
  }

  Widget _buildNameField(ReferralFormManager formManager) {
    return Focus(
      focusNode: _nameFocusNode,
      child: TextInputWidget(
        controller: _nameController,
        hintText: LocaleKeys.enterReferralRequesterName.tr(context: context),
        labelText: LocaleKeys.requesterName.tr(context: context),
        keyboardType: TextInputType.text,
        errorMessage: formManager.errors.requesterName,
        isAllowLeadingIcon: true,
        leadingIcon: AppAssets.user_circle,
        hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.requesterName),
        padding: EdgeInsets.symmetric(
          vertical: ResponsiveExtension(12).h,
          horizontal: ResponsiveExtension(16).h,
        ),
        onChange: (value) {
          formManager.updateRequesterName(value ?? '');
        },

      ).paddingSymmetrical(0, 8),
    );
  }
  Widget _buildRelationshipField(BuildContext context, ReferralFormManager formManager) {
    return DropdownWidget(
      labelText: LocaleKeys.relationship.tr(context: context),
      hintText: formManager.formData.relationship?.text ?? LocaleKeys.selectRelation.tr(context: context),
      isEnable: false,
      selectedValue: formManager.formData.relationship?.text ?? LocaleKeys.selectRelation.tr(context: context),
      errorMessage: formManager.errors.relationship,
      hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.relationship),
      hasSelectionCustomIcon: false,
      labelColor: AppColors.textColor,
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
      leadingIcon: AppAssets.user_circle,
      dropdownItems: [],
    ).paddingSymmetrical(0, 8).onPress(() {
      _showRelationshipBottomSheet(context, formManager);
    });
  }

  Widget _buildOtherNameField(ReferralFormManager formManager) {
    return Focus(
      focusNode: _otherNameFocusNode,
      child: TextInputWidget(
        controller: _otherNameController,
        keyboardType: TextInputType.text,
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        hintText: LocaleKeys.otherNameHint.tr(context: context),
        labelText: LocaleKeys.otherName.tr(context: context),
        errorMessage: formManager.errors.otherRelationshipName,
        onChange: (value) {
          formManager.updateOtherRelationshipName(value ?? '');
        },
      ).paddingSymmetrical(0, 4),
    );
  }

  bool _showOtherNameField(ReferralFormManager formManager) {
    return formManager.formData.relationship != null &&
        formManager.formData.relationship?.iD == 5;
  }

  void _showRelationshipBottomSheet(BuildContext context, ReferralFormManager formManager) {
    final hmgServicesVM = context.read<HmgServicesViewModel>();

    showCommonBottomSheetWithoutHeight(
      context,
      title: LocaleKeys.selectRelation.tr(context: context),
      child: Consumer<HmgServicesViewModel>(
        builder: (context, hmgServicesVM, child) {
          if (hmgServicesVM.relationTypes.isEmpty) {
            return const Center(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Text('No relationships available'),
              ),
            );
          }

          return DecoratedBox(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                customBorder:  BorderRadius.all(Radius.circular(24.h)) ,

            ), child: ListView.builder(
            shrinkWrap: true,
            padding: EdgeInsets.all(16.h),
            physics: const BouncingScrollPhysics(),
            itemBuilder: (context, index) {
              final relationship = hmgServicesVM.relationTypes[index];
              return ListTile(
                title:relationship.text?.toText14(),
                onTap: () {
                  formManager.updateRelationship(relationship);
                  Navigator.pop(context);
                },
              );
            },
            //separatorBuilder: (context, index) => const Divider(),
            itemCount: hmgServicesVM.relationTypes.length,
          ));
        },
      ),
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }

  @override
  void dispose() {
    _nameController.dispose();
    _phoneController.dispose();
    _otherNameController.dispose();
    _nameFocusNode.dispose();
    _phoneFocusNode.dispose();
    _otherNameFocusNode.dispose();
    super.dispose();
  }
}