import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.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/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:provider/provider.dart';
import 'package:hmg_patient_app_new/core/app_assets.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 SearchEReferralFormForm extends StatefulWidget {
  final VoidCallback? onFormValidated;
  const SearchEReferralFormForm({super.key, this.onFormValidated});

  @override
  State<SearchEReferralFormForm> createState() => SearchEReferralFormFormState();
}

class SearchEReferralFormFormState extends State<SearchEReferralFormForm> {
  late TextEditingController _searchController;
  late TextEditingController _phoneController;
  late FocusNode _searchFocusNode;
  late FocusNode _phoneFocusNode;

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

    _searchController = TextEditingController();
    _phoneController = TextEditingController();
    _searchFocusNode = FocusNode();
    _phoneFocusNode = FocusNode();

    // Initialize controllers with current values from form manager
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        final formManager = context.read<ReferralFormManager>();
        _searchController.text = formManager.searchValue ?? '';
        _phoneController.text = formManager.searchPhone ?? '';
        // _searchFocusNode.requestFocus();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ReferralFormManager>(
      builder: (context, formManager, child) {
        return Padding(
          padding: const EdgeInsets.symmetric(horizontal: 24.0),
          child: ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: [
              // const SizedBox(height: 12),
              _buildSelectionField(context, formManager),
              _buildNameField(formManager),
              _buildPhoneField(formManager),
            ],
          ),
        );
      },
    );
  }

  Widget _buildNameField(ReferralFormManager formManager) {
    return Focus(
      focusNode: _searchFocusNode,
      autofocus: true,
      child: TextInputWidget(
        controller: _searchController,
        hintText: formManager.searchCriteria == 0 ? LocaleKeys.enterIdentificationNumber.tr() : LocaleKeys.enterReferralNumber.tr(),
        labelText: formManager.searchCriteria == 0 ? LocaleKeys.identificationNumber.tr() : LocaleKeys.referralNumber.tr(),
        keyboardType: TextInputType.number,
        fontFamily: "Poppins",
        errorMessage: formManager.errors.searchValue,
        padding: EdgeInsets.symmetric(vertical: 14.h, horizontal: 16.h),

        hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.searchValue),
        onChange: (value) {
          formManager.updateSearchValue(value ?? '');
          //_validateForm(formManager);
        },
      ).paddingSymmetrical(0, 8),
    );
  }

  Widget _buildPhoneField(ReferralFormManager formManager) {
    return Focus(
      focusNode: _phoneFocusNode,
      autofocus: false,
      child: TextInputWidget(
        autoFocus: false,
        labelText: LocaleKeys.phoneNumber.tr(),
        hintText: LocaleKeys.phoneHint.tr(),
        controller: _phoneController,
        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
        keyboardType: TextInputType.number,
        fontFamily: "Poppins",
        onChange: (value) {
          formManager.updateSearchPhone(value ?? '');
          // _validateForm(formManager);
        },
        // onSubmitted: (value) {
        //   formManager.updateRequesterPhone(value ?? '');
        //   _validateForm(formManager);
        // },
        onCountryChange: (value) {
          formManager.updateCountryEnum(value);
          // _validateForm(formManager);
        },
        prefix: '966',
        isBorderAllowed: false,
        isAllowLeadingIcon: true,
        fontSize: 13,
        isCountryDropDown: true,
        leadingIcon: AppAssets.smart_phone,
        errorMessage: formManager.errors.searchPhone,
        hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.searchPhone),
      ).paddingSymmetrical(0, 8),
    );
  }

  Widget _buildSelectionField(BuildContext context, ReferralFormManager formManager) {
    return DropdownWidget(
      labelText: LocaleKeys.selectCriteria.tr(),
      hintText: formManager.searchCriteria == 0 ? LocaleKeys.identificationNumber.tr() : LocaleKeys.referralNumber.tr(),
      isEnable: false,
      hasSelectionCustomIcon: false,
      labelColor: Colors.black,
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
      leadingIcon: AppAssets.search_icon,
      dropdownItems: [],
    ).paddingSymmetrical(0, 8).onPress(() {
      _showCriteriaBottomSheet(context, formManager);
    });
  }

  void _showCriteriaBottomSheet(BuildContext context, ReferralFormManager formManager) {
    final criteriaList = [
      {0:  LocaleKeys.identificationNumber.tr()},
      {1:  LocaleKeys.referralNumber.tr()},
    ];

    showCommonBottomSheetWithoutHeight(
      context,
      title:  LocaleKeys.selectCriteria.tr(),
      child: ListView.separated(
        shrinkWrap: true,
        physics: const BouncingScrollPhysics(),
        itemBuilder: (context, index) {
          final criteria = criteriaList[index];
          final criteriaKey = criteria.keys.first;
          final criteriaValue = criteria.values.first;

          return ListTile(
            leading: Radio<int>(
              value: criteriaKey,
              groupValue: formManager.searchCriteria,
              onChanged: (value) {
                if (value != null) {
                  formManager.updateSearchCriteria(value);
                  _searchController.clear();
                  _validateForm(formManager);
                  Navigator.pop(context);
                }
              },
            ),
            title: Text(criteriaValue),
            onTap: () {
              formManager.updateSearchCriteria(criteriaKey);
              _searchController.clear();
              _validateForm(formManager);
              Navigator.pop(context);
            },
          );
        },
        separatorBuilder: (context, index) => const Divider(),
        itemCount: criteriaList.length,
      ),
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }

  void _validateForm(ReferralFormManager formManager) {
    // Trigger validation
    formManager.validateSearchForm();

    // Notify parent if form validation state changes
    widget.onFormValidated?.call();
  }

  @override
  void dispose() {
    _searchController.dispose();
    _phoneController.dispose();
    _searchFocusNode.dispose();
    _phoneFocusNode.dispose();
    super.dispose();
  }
}
