import 'dart:io';
import 'dart:ui' as ui;

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/enums.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/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/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';

class GenericBottomSheet extends StatefulWidget {
  final String? countryCode;
  final String? initialPhoneNumber;
  final List<Widget> buttons;
  final TextEditingController? textController;
  final bool isForEmail;
  final Function(CountryEnum)? onCountryChange;
  final bool isEnableCountryDropdown;
  final bool isFromSavedLogin;
  final Function(String?)? onChange;
  final bool autoFocus;
  final String? phoneNumberError;
  final String? emailError;

  // FocusNode myFocusNode;

  const GenericBottomSheet({
    super.key,
    this.countryCode = "",
    this.initialPhoneNumber = "",
    required this.buttons,
    this.textController,
    this.isForEmail = false,
    this.onCountryChange,
    this.isEnableCountryDropdown = false,
    this.isFromSavedLogin = false,
    this.onChange,
    this.autoFocus = false,
    this.phoneNumberError,
    this.emailError,
    // required this.myFocusNode
  });

  @override
  GenericBottomSheetState createState() => GenericBottomSheetState();
}

class GenericBottomSheetState extends State<GenericBottomSheet> {
  late FocusNode _textFieldFocusNode;

  @override
  void initState() {
    super.initState();
    _textFieldFocusNode = FocusNode();

    if (!widget.isForEmail && widget.textController != null) {
      widget.textController!.text = widget.initialPhoneNumber ?? "";
    }

    // Auto focus the text field if specified
    if (widget.autoFocus && widget.textController != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _textFieldFocusNode.requestFocus();
      });
    }
  }

  @override
  void dispose() {
    _textFieldFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      bottom: Platform.isIOS ? false : true,
      child: GestureDetector(
        onTap: () {
          _textFieldFocusNode.unfocus();
          FocusScope.of(context).unfocus();
        },
        child: Directionality(
          textDirection: ui.TextDirection.ltr,
          child: Container(
            padding: EdgeInsets.all(24.h),
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.bgScaffoldColor,
              borderRadius: 16.r,
              customBorder: BorderRadius.only(topLeft: Radius.circular(16.r), topRight: Radius.circular(16.r)),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // Title
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Flexible(
                        child: widget.isFromSavedLogin
                            ? LocaleKeys.receiveOtpToast.tr().toText24()
                            : widget.isForEmail
                                ? LocaleKeys.enterEmail.tr().toText24()
                                : LocaleKeys.enterPhoneNumber.tr().toText24()),
                    InkWell(
                      onTap: () {
                        // Dismiss keyboard before closing
                        _textFieldFocusNode.unfocus();
                        FocusScope.of(context).unfocus();
                        Navigator.of(context).pop();
                      },
                      child: Padding(
                        padding: EdgeInsets.only(top: 10.h),
                        child: Utils.buildSvgWithAssets(
                          icon: AppAssets.cross_circle,
                          height: 24.h,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 8.h),
                // Subtitle
                widget.isFromSavedLogin
                    ? LocaleKeys.pleaseChooseOption.tr().toText16()
                    : widget.isForEmail
                        ? LocaleKeys.enterEmailDesc.tr().toText16()
                        : LocaleKeys.enterPhoneDesc.tr().toText16(),

                if (widget.isFromSavedLogin)
                  ...[]
                else ...[
                  widget.textController != null
                      ? TextInputWidget(
                          labelText: widget.isForEmail ? LocaleKeys.email.tr() : LocaleKeys.phoneNumber.tr(),
                          hintText: widget.isForEmail ? "demo@gmail.com" : "5xxxxxxxx",
                          controller: widget.textController!,
                          focusNode: _textFieldFocusNode,
                          autoFocus: widget.autoFocus,
                          padding: EdgeInsets.all(8.h),
                          keyboardType: widget.isForEmail ? TextInputType.emailAddress : TextInputType.number,
                          onChange: (value) {
                            if (widget.onChange != null) {
                              if (Utils.isArabicText(value!)) {
                                value = Utils.toEnglishNumbers(value);
                              }
                              widget.onChange!(value);
                            }
                          },
                          onCountryChange: (value) {
                            if (widget.onCountryChange != null) {
                              widget.onCountryChange!(value);
                            }
                          },
                          isEnable: true,
                          isReadOnly: widget.isFromSavedLogin,
                          prefix: widget.isForEmail ? null : widget.countryCode,
                          isBorderAllowed: false,
                          isAllowLeadingIcon: true,
                          fontSize: 14.f,
                          isCountryDropDown: widget.isEnableCountryDropdown,
                          leadingIcon: widget.isForEmail ? AppAssets.email : AppAssets.smart_phone,
                          fontFamily: "Poppins",
                          hasError: widget.isForEmail ? (widget.emailError != null) : (widget.phoneNumberError != null),
                          errorMessage: widget.isForEmail ? widget.emailError : widget.phoneNumberError,
                        )
                      : SizedBox(),
                ],

                SizedBox(height: 24.h),
                ...widget.buttons,
              ],
            ),
          ),
        ),
      ),
    );
  }
}
