import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/core/app_state.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/features/hmg_services/models/resq_models/get_all_cities_resp_model.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/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';

import '../../../core/dependencies.dart' show getIt;

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

  @override
  State<PatientInformationStep> createState() => PatientInformationStepState();
}

class PatientInformationStepState extends State<PatientInformationStep> {
  late TextEditingController _identificationController;
  late TextEditingController _nameController;
  late TextEditingController _phoneController;

  late FocusNode _identificationFocusNode;
  late FocusNode _nameFocusNode;
  late FocusNode _phoneFocusNode;

  late ReferralFormManager _formManager;

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

    _identificationController = TextEditingController();
    _nameController = TextEditingController();
    _phoneController = TextEditingController();

    _identificationFocusNode = FocusNode();
    _nameFocusNode = FocusNode();
    _phoneFocusNode = FocusNode();

    // Initialize controllers with current values
    _identificationController.text = _formManager.formData.patientIdentification ?? '';
    _nameController.text = _formManager.formData.patientName ?? '';
    _phoneController.text = _formManager.formData.patientPhone ?? '';

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

  @override
  Widget build(BuildContext context) {
    return Consumer<ReferralFormManager>(
      builder: (context, formManager, child) {
        return Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: ListView(
            padding: EdgeInsets.zero,
            physics: const BouncingScrollPhysics(),
            children: [
              const SizedBox(height: 12),
              _buildSectionTitle(LocaleKeys.patientInfo.tr(context: context)),
              const SizedBox(height: 12),
              _buildIdentificationField(formManager),
              _buildPatientNameField(formManager),
              _buildPatientPhoneField(formManager),
              const SizedBox(height: 20),
              _buildSectionTitle(LocaleKeys.patientLocation.tr(context: context)),
              _buildPatientCityField(context, formManager),
            ],
          ),
        );
      },
    );
  }

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

  Widget _buildIdentificationField(ReferralFormManager formManager) {
    return TextInputWidget(
      controller: _identificationController,
      focusNode: _identificationFocusNode,
      padding: EdgeInsets.symmetric(
        vertical: ResponsiveExtension(12).h,
        horizontal: ResponsiveExtension(16).h,
      ),
      hintText: LocaleKeys.enterIdentificationNumber.tr(context: context),
      labelText: LocaleKeys.identificationNumber.tr(context: context),
      errorMessage: formManager.errors.patientIdentification,
      hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.patientIdentification),
      onChange: (value) {
        formManager.updatePatientIdentification(value ?? '');
      },
      onSubmitted: (value) {
        _nameFocusNode.requestFocus();
      },
    ).paddingSymmetrical(0, 4);
  }

  Widget _buildPatientNameField(ReferralFormManager formManager) {
    return TextInputWidget(
      controller: _nameController,
      focusNode: _nameFocusNode,
      padding: EdgeInsets.symmetric(vertical: ResponsiveExtension(12).h, horizontal: ResponsiveExtension(16).h),
      hintText: LocaleKeys.patientName.tr(context: context),
      labelText: LocaleKeys.name.tr(context: context),
      keyboardType: TextInputType.text,
      errorMessage: formManager.errors.patientName,
      hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.patientName),
      onChange: (value) {
        formManager.updatePatientName(value ?? '');
      },
      onSubmitted: (value) {
        _phoneFocusNode.requestFocus();
      },
    ).paddingSymmetrical(0, 4);
  }

  Widget _buildPatientPhoneField(ReferralFormManager formManager) {
    return Directionality(
      textDirection: ui.TextDirection.ltr,
      child: TextInputWidget(
        labelText: LocaleKeys.phoneNumber.tr(context: context),
        hintText: "5xxxxxxxx",
        controller: _phoneController,
        focusNode: _phoneFocusNode,
        padding: const EdgeInsets.all(8),
        keyboardType: TextInputType.number,
        fontFamily: "Poppins",
        onChange: (value) {
          formManager.updatePatientPhone(value ?? '');
        },
        onCountryChange: (value) {
          formManager.updatePatientCountryEnum(value);
        },
        prefix: '966',
        isBorderAllowed: false,
        isAllowLeadingIcon: true,
        fontSize: 13,
        isCountryDropDown: true,
        leadingIcon: AppAssets.smart_phone,
        errorMessage: formManager.errors.patientPhone,
        hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.patientPhone),
      ).paddingSymmetrical(0, 8),
    );
  }

  Widget _buildPatientCityField(BuildContext context, ReferralFormManager formManager) {
    return DropdownWidget(
      labelText: LocaleKeys.city.tr(),
      hintText: getLocaleDescription(formManager.formData.patientCity) ?? LocaleKeys.selectCity.tr(context: context),
      isEnable: false,
      hasSelectionCustomIcon: true,
      labelColor: Colors.black,
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
      selectionCustomIcon: AppAssets.arrow_down,
      leadingIcon: AppAssets.globe,
      dropdownItems: [],
      errorMessage: formManager.errors.patientCity,
      hasError: !ValidationUtils.isNullOrEmpty(formManager.errors.patientCity),
    ).paddingSymmetrical(0, 4).onPress(() {
      _showCityBottomSheet(context, formManager);
    });
  }

  String? getLocaleDescription(GetAllCitiesResponseModel? patientCity) {
    return getIt.get<AppState>().isArabic() ? patientCity?.descriptionN : patientCity?.description;
  }

  void _showCityBottomSheet(BuildContext context, ReferralFormManager formManager) {
    showCommonBottomSheetWithoutHeight(
      context,
      title: LocaleKeys.selectCity.tr(context: context),
      child: Consumer<HmgServicesViewModel>(
        builder: (context, hmgServicesVM, child) {
          final cities = hmgServicesVM.getAllCitiesList;
          if (cities == null || cities.isEmpty) {
            return const Center(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Text('No cities available'),
              ),
            );
          }

          return DecoratedBox(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: Colors.white,
                customBorder: BorderRadius.all(Radius.circular(24.h)),
              ),
              child: ListView.builder(
                shrinkWrap: true,
                padding: EdgeInsets.all(16.h),
                physics: const BouncingScrollPhysics(),
                itemBuilder: (context, index) {
                  final city = cities[index];
                  return ListTile(
                    title: (getLocaleDescription(city) ?? 'Unknown').toText14(),
                    onTap: () {
                      formManager.updatePatientCity(city);
                      Navigator.pop(context);
                    },
                  );
                },
                // separatorBuilder: (context, index) => const Divider(),
                itemCount: cities.length,
              ));
        },
      ),
      useSafeArea: true,
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }

  @override
  void dispose() {
    _identificationController.dispose();
    _nameController.dispose();
    _phoneController.dispose();
    _identificationFocusNode.dispose();
    _nameFocusNode.dispose();
    _phoneFocusNode.dispose();
    super.dispose();
  }
}
