import 'dart:ui' as ui;

import 'package:clarity_flutter/clarity_flutter.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
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/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.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/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/date_range_calender.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/models/calendar_design_type.dart';
import 'package:hmg_patient_app_new/widgets/dropdown/country_dropdown_widget.dart';
import 'package:hmg_patient_app_new/widgets/time_picker_widget.dart';

class TextInputWidget extends StatelessWidget {
  final String labelText;
  final String hintText;
  final TextEditingController? controller;
  final Function(String?)? onChange;
  final Function(bool)? onCalendarTypeChanged;
  final String? prefix;
  final bool isEnable;
  final bool isBorderAllowed;
  final bool isAllowRadius;
  final bool isReadOnly;
  final TextInputType keyboardType;
  final FocusNode? focusNode;
  final bool autoFocus;
  final EdgeInsetsGeometry? padding;
  final bool isAllowLeadingIcon;
  final String? leadingIcon;
  final bool isCountryDropDown;
  final bool hasError;
  final String? errorMessage;
  final Function(CountryEnum)? onCountryChange;
  final SelectionTypeEnum? selectionType;
  final double? fontSize;
  final bool? isWalletAmountInput;
  final Widget? suffix;
  final Color? labelColor;
  final Function(String)? onSubmitted;
  final String? btnTitle;

  // new multiline options
  final bool isMultiline;
  final int minLines;
  final int maxLines;
  final Color? hintColor;
  final bool? isHideSwitcher;
  final bool? isArrowTrailing;
  final bool leadingIconNeedsContainer;
  final String? fontFamily;

  // final List<Country> countryList;
  // final Function(Country)? onCountryChange;

  TextInputWidget({
    super.key,
    required this.labelText,
    required this.hintText,
    this.controller,
    this.onChange,
    this.onCalendarTypeChanged,
    this.prefix,
    this.isEnable = true,
    this.isBorderAllowed = true,
    this.isAllowRadius = true,
    this.isReadOnly = false,
    this.keyboardType = TextInputType.number,
    this.focusNode,
    this.autoFocus = false,
    this.padding,
    this.isAllowLeadingIcon = false,
    this.leadingIcon,
    this.isCountryDropDown = false,
    this.hasError = false,
    this.errorMessage,
    this.onCountryChange,
    this.selectionType,
    this.fontSize,
    this.isWalletAmountInput = false,
    this.suffix,
    this.labelColor,
    this.onSubmitted,
    this.hintColor,
    // multiline defaults
    this.isMultiline = false,
    this.minLines = 3,
    this.maxLines = 6,
    this.isHideSwitcher,
    this.isArrowTrailing,
    this.fontFamily,
    this.leadingIconNeedsContainer = true,
    // this.countryList = const [],
    // this.onCountryChange,
    this.btnTitle,
  });

  final FocusNode _focusNode = FocusNode();

  // KeyboardActionsConfig get _keyboardActionsConfig {
  //   return KeyboardActionsConfig(
  //     keyboardActionsPlatform: KeyboardActionsPlatform.ALL,
  //     keyboardBarColor: const Color(0xFFCAD1D9), //Apple keyboard color
  //     actions: [
  //       KeyboardActionsItem(
  //         focusNode: focusNode ?? _focusNode,
  //         toolbarButtons: [
  //           (node) {
  //             return GestureDetector(
  //               onTap: () => node.unfocus(),
  //               child: Container(
  //                 padding: const EdgeInsets.all(12.0),
  //                 child: "Done".toText16(isBold: true, color: AppColors.infoColor),
  //               ),
  //             );
  //           }
  //         ],
  //       ),
  //     ],
  //   );
  // }

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();
    final errorColor = AppColors.primaryRedColor;

    // Determine border: always show red border on error, otherwise respect isBorderAllowed
    BorderSide? borderSide;
    if (hasError) {
      // Always show red border when there's an error
      borderSide = BorderSide(color: errorColor, width: 1);
    } else if (isBorderAllowed) {
      // Show normal border when allowed and no error
      borderSide = BorderSide(color: const Color(0xffefefef), width: 1);
    } else {
      // No border
      borderSide = null;
    }

    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: padding,
          // height: isMultiline ? null : 64.h,
          alignment: Alignment.center,
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
            color: AppColors.whiteColor,
            borderRadius: isAllowRadius ? (12.r) : null,
            side: borderSide,
          ),
          child: Row(
            textDirection: Directionality.of(context),
            children: [
              if (isAllowLeadingIcon && leadingIcon != null && !isCountryDropDown) _buildLeadingIcon(context),
              isCountryDropDown
                  ? CustomCountryDropdown(
                      countryList: CountryEnum.values,
                      onCountryChange: onCountryChange,
                      isFromBottomSheet: isCountryDropDown,
                      isEnableTextField: true,
                      onPhoneNumberChanged: onChange,
                      // textField: _buildTextField(context),
                    )
                  : Expanded(
                      child: Row(
                        children: [
                          Expanded(
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _buildLabelText(labelColor).paddingOnly(
                                  right: (appState.isArabic() ? 10 : 10),
                                  left: (!appState.isArabic() ? 10 : 10),
                                ),
                                Row(
                                  children: [
                                    Expanded(
                                      child: _buildTextField(context).paddingOnly(
                                        right: (appState.getLanguageCode() == "ar" ? 10 : 0),
                                        left: (appState.getLanguageCode() == "en" ? 10 : 0),
                                      ),
                                    )
                                  ],
                                ),
                              ],
                            ),
                          ),
                          (suffix != null) ? suffix! : SizedBox.shrink()
                        ],
                      ),
                    ),
              if (selectionType == SelectionTypeEnum.calendar) _buildTrailingIcon(context, isArrowTrailing: isArrowTrailing ?? false),
              if (selectionType == SelectionTypeEnum.time) _buildTimePickerIcon(context, isArrowTrailing: isArrowTrailing ?? false),
              if (selectionType == SelectionTypeEnum.search) _buildTrailingIconForSearch(context),
            ],
          ),
        ),
        if (errorMessage != null && errorMessage!.isNotEmpty)
          Padding(
            padding: EdgeInsets.only(top: 4.h, left: 12.h), // Adjust padding as needed
            child: Text(
              errorMessage!,
              style: TextStyle(
                color: errorColor,
                fontSize: 12.f,
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildLeadingIcon(BuildContext context) {
    if (leadingIconNeedsContainer) {
      return Container(
          height: 40.h,
          width: 40.h,
          // margin: EdgeInsets.symmetric(horizontal: 10.w),
          padding: EdgeInsets.all(8.h),
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
            borderRadius: 12.r,
            color: AppColors.greyColor,
          ),
          child: Utils.buildSvgWithAssets(icon: leadingIcon!, applyThemeColor: false));
    }
    return Utils.buildSvgWithAssets(icon: leadingIcon!, applyThemeColor: false, height: 40.h, width: 40.h);
  }

  Widget _buildTrailingIcon(BuildContext context, {bool isArrowTrailing = false}) {
    return Container(
      height: 40.h,
      width: 40.w,
      margin: EdgeInsets.zero,
      padding: EdgeInsets.all(8.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(borderRadius: 12.r, color: AppColors.whiteColor),
      child: GestureDetector(
        onTap: () async {
          showCommonBottomSheetWithoutHeight(
            title: LocaleKeys.selectDate.tr(context: context),
            context,
            child: DateRangeSelector(
                onRangeSelected: (DateTime? start, DateTime? end) {
                  var picked = start.toString().split(" ").first;
                  if (picked != null && onChange != null) {
                    onChange!(picked.toString());
                  }
                },
                designType: CalendarDesignType.designV2,
                showCalendarToggle: isHideSwitcher == true ? false : true,
                onCalendarTypeChanged: onCalendarTypeChanged,
                btnTitle: btnTitle ?? LocaleKeys.done.tr()),
            isFullScreen: false,
            isCloseButtonVisible: true,
            callBackFunc: () {
              // Don't reset calendar type - persist user's preference
            },
          );
        },
        child: Utils.buildSvgWithAssets(icon: isArrowTrailing ? AppAssets.arrow_down : AppAssets.calendar),
      ),
    );
  }

  Widget _buildTimePickerIcon(BuildContext context, {bool isArrowTrailing = false}) {
    return Container(
      height: 40.h,
      width: 40.h,
      margin: EdgeInsets.zero,
      padding: EdgeInsets.all(8.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        borderRadius: 12.r,
        color: AppColors.whiteColor,
      ),
      child: GestureDetector(
        onTap: () async {
          // Parse existing time if available
          TimeOfDay? initialTime;
          if (controller?.text.isNotEmpty ?? false) {
            initialTime = TimePickerWidget.parseTime(controller!.text);
          }

          final picked = await TimePickerWidget.show(
            context,
            initialTime: initialTime,
            use24HourFormat: true,
            onTimeSelected: (time) {
              if (onChange != null) {
                final formattedTime = TimePickerWidget.formatTime(time, use24HourFormat: true);
                onChange!(formattedTime);
              }
            },
          );

          // Update controller if time was picked
          if (picked != null && controller != null) {
            controller!.text = TimePickerWidget.formatTime(picked, use24HourFormat: true);
          }
        },
        child: Utils.buildSvgWithAssets(icon: isArrowTrailing ? AppAssets.arrow_down : AppAssets.alarm_clock_icon),
      ),
    );
  }

  Widget _buildLabelText(Color? labelColor) {
    return labelText.toText12(isBold: true, color: labelColor ?? AppColors.inputLabelTextColor);
  }

  // Original _buildTextField - kept as backup reference
  // Widget _buildTextFieldOriginal(BuildContext context) {
  //   double fontS = fontSize ?? 14.f;
  //   final isArabic = getIt.get<AppState>().isArabic();
  //
  //   return Builder(
  //     builder: (context) {
  //       return Directionality(
  //         textDirection: isArabic ? ui.TextDirection.rtl : ui.TextDirection.ltr,
  //         child: Localizations.override(
  //           context: context,
  //           locale: const Locale('en', 'US'), // Force English locale for TextField
  //           child: TextField(
  //             hintLocales: const [Locale('en', 'US')],
  //             enabled: isEnable,
  //             scrollPadding: EdgeInsets.zero,
  //             keyboardType: isMultiline ? TextInputType.multiline : (isWalletAmountInput! ? const TextInputType.numberWithOptions(decimal: true) : keyboardType),
  //             controller: controller,
  //             readOnly: isReadOnly,
  //             textAlignVertical: TextAlignVertical.top,
  //             textAlign: isArabic ? TextAlign.right : TextAlign.left,
  //             textDirection: ui.TextDirection.ltr,
  //             onChanged: onChange,
  //             focusNode: focusNode ?? _focusNode,
  //             autofocus: autoFocus,
  //             textInputAction: TextInputAction.done,
  //             cursorHeight: isWalletAmountInput! ? 40.h : 20.h,
  //             maxLength: isWalletAmountInput! ? 7 : 100,
  //             inputFormatters: isWalletAmountInput!
  //                 ? [
  //                     _ThousandSeparatorInputFormatter(),
  //                   ]
  //                 : null,
  //             onTapOutside: (event) {
  //               FocusManager.instance.primaryFocus?.unfocus();
  //             },
  //             onSubmitted: onSubmitted,
  //             minLines: isMultiline ? minLines : 1,
  //             maxLines: isMultiline ? maxLines : 1,
  //             style: TextStyle(
  //               fontSize: fontS,
  //               height: isMultiline ? 1.2 : (isWalletAmountInput! ? 1 / 4 : 0),
  //               fontWeight: FontWeight.w600,
  //               color: AppColors.textColor,
  //               letterSpacing: -1,
  //               fontFamily: fontFamily,
  //               locale: const Locale('en', 'US'), // Force English locale for text style
  //             ),
  //             decoration: InputDecoration(
  //               counterText: "",
  //               isDense: true,
  //               hintText: hintText,
  //               hintStyle: TextStyle(
  //                 fontFamily: isArabic ? 'CairoArabic' : 'Poppins',
  //                 fontSize: 14.f,
  //                 height: 21 / 16,
  //                 fontWeight: FontWeight.w600,
  //                 color: hintColor != null ? AppColors.textColor : Color(0xff898A8D),
  //                 letterSpacing: -0.75,
  //               ),
  //               prefixIconConstraints: BoxConstraints(minWidth: 30.h),
  //               prefixIcon: prefix == null ? null : "+${prefix!}".toText14(letterSpacing: -1, color: AppColors.textColor, isBold: true),
  //               contentPadding: EdgeInsets.only(right: isArabic ? 10.w : 0),
  //               border: InputBorder.none,
  //               focusedBorder: InputBorder.none,
  //               enabledBorder: InputBorder.none,
  //             ),
  //           ),
  //         ),
  //       );
  //     },
  //   );
  // }

  Widget _buildTextField(BuildContext context) {
    double fontS = fontSize ?? 14.f;
    final isArabic = getIt.get<AppState>().isArabic();

    // Note: Error border is already handled by the parent Container in build() method
    // The Container shows red border when hasError is true

    return Builder(
      builder: (context) {
        return Directionality(
          textDirection: isArabic ? ui.TextDirection.rtl : ui.TextDirection.ltr,
          child: Localizations.override(
            context: context,
            locale: const Locale('en', 'US'), // Force English locale for TextField
            child: ClarityUnmask(
              child: TextField(
                hintLocales: const [Locale('en', 'US')],
                enabled: isEnable,
                scrollPadding: EdgeInsets.zero,
                keyboardType: isMultiline
                    ? TextInputType.multiline
                    : (isWalletAmountInput! ? const TextInputType.numberWithOptions(decimal: true) : keyboardType),
                controller: controller,
                readOnly: isReadOnly,
                textAlignVertical: TextAlignVertical.top,
                textAlign: isArabic ? TextAlign.right : TextAlign.left,
                textDirection: ui.TextDirection.ltr,
                onChanged: onChange,
                focusNode: focusNode ?? _focusNode,
                autofocus: autoFocus,
                textInputAction: TextInputAction.done,
                cursorHeight: isWalletAmountInput! ? 40.h : 20.h,
                maxLength: isWalletAmountInput! ? 7 : 100,
                inputFormatters: isWalletAmountInput!
                    ? [
                        _ThousandSeparatorInputFormatter(),
                      ]
                    : null,
                onTapOutside: (event) {
                  FocusManager.instance.primaryFocus?.unfocus();
                },
                onSubmitted: onSubmitted,
                minLines: isMultiline ? minLines : 1,
                maxLines: isMultiline ? maxLines : 1,
                style: TextStyle(
                  fontSize: fontS,
                  height: isMultiline ? 1.2 : (isWalletAmountInput! ? 1 / 4 : 0),
                  fontWeight: FontWeight.w600,
                  color: AppColors.textColor,
                  letterSpacing: -1,
                  fontFamily: fontFamily,
                  locale: const Locale('en', 'US'), // Force English locale for text style
                ),
                decoration: InputDecoration(
                  counterText: "",
                  isDense: true,
                  hintText: hintText,
                  hintStyle: TextStyle(
                    fontFamily: isArabic ? 'CairoArabic' : 'Poppins',
                    fontSize: 14.f,
                    height: 21 / 16,
                    fontWeight: FontWeight.w600,
                    color: hintColor != null ? AppColors.textColor : Color(0xff898A8D),
                    letterSpacing: -0.75,
                  ),
                  prefixIconConstraints: BoxConstraints(minWidth: 30.h),
                  prefixIcon: prefix == null ? null : "+${prefix!}".toText14(letterSpacing: -1, color: AppColors.textColor, isBold: true),
                  contentPadding: EdgeInsets.only(right: isArabic ? 10.w : 0),
                  border: InputBorder.none,
                  focusedBorder: InputBorder.none,
                  enabledBorder: InputBorder.none,
                  // Show red border when field has error - but we handle this in the parent Container
                  // The parent Container in build() already shows red border based on hasError flag
                ),
              ),
            ),
          ),
        );
      },
    );

    //   TextField(
    //   hintLocales: const [Locale('en', 'US')],
    //   enabled: isEnable,
    //   scrollPadding: EdgeInsets.zero,
    //   keyboardType: isMultiline ? TextInputType.multiline : keyboardType,
    //   controller: controller,
    //   readOnly: isReadOnly,
    //   textAlignVertical: TextAlignVertical.top,
    //   textAlign: TextAlign.left,
    //   textDirection: TextDirection.ltr,
    //   onChanged: onChange,
    //   focusNode: focusNode ?? _focusNode,
    //   autofocus: autoFocus,
    //   textInputAction: TextInputAction.done,
    //   cursorHeight: isWalletAmountInput! ? 40.h : 20.h,
    //   onTapOutside: (event) {
    //     FocusManager.instance.primaryFocus?.unfocus();
    //   },
    //   onSubmitted: onSubmitted,
    //   minLines: isMultiline ? minLines : 1,
    //   maxLines: isMultiline ? maxLines : 1,
    //   style: TextStyle(
    //     fontSize: fontS,
    //     height: isMultiline ? 1.2 : (isWalletAmountInput! ? 1 / 4 : 0),
    //     isBold: true,
    //     color: AppColors.textColor,
    //     letterSpacing: -1,
    //   ),
    //   decoration: InputDecoration(
    //     isDense: true,
    //     hintText: hintText,
    //     hintStyle: TextStyle(
    //         fontSize: 14.f,
    //         height: 21 / 16,
    //         isBold: true,
    //         color: hintColor != null ? AppColors.textColor : Color(0xff898A8D),
    //         letterSpacing: -0.75),
    //     prefixIconConstraints: BoxConstraints(minWidth: 30.h),
    //     prefixIcon: prefix == null ? null : "+${prefix!}".toText14(letterSpacing: -1, color: AppColors.textColor, isBold: true),
    //     contentPadding: EdgeInsets.zero,
    //     border: InputBorder.none,
    //     focusedBorder: InputBorder.none,
    //     enabledBorder: InputBorder.none,
    //   ),
    // );
  }

  _buildTrailingIconForSearch(BuildContext context) {
    return Container(
      height: 40.h,
      width: 40.h,
      margin: EdgeInsets.zero,
      padding: EdgeInsets.all(8.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(borderRadius: 12.r, color: AppColors.whiteColor),
      child: Utils.buildSvgWithAssets(icon: AppAssets.search_icon),
    );
  }
}

class _ThousandSeparatorInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    // Remove all commas to get the raw number
    String newText = newValue.text.replaceAll(',', '');

    // Allow only digits and one decimal point
    if (newText.isNotEmpty && !RegExp(r'^\d*\.?\d{0,2}$').hasMatch(newText)) {
      return oldValue;
    }

    // Split into integer and decimal parts
    String integerPart;
    String decimalPart = '';

    if (newText.contains('.')) {
      final parts = newText.split('.');
      integerPart = parts[0];
      decimalPart = '.${parts[1]}';
    } else {
      integerPart = newText;
    }

    // Add thousand separators to the integer part
    if (integerPart.isNotEmpty) {
      final buffer = StringBuffer();
      int count = 0;
      for (int i = integerPart.length - 1; i >= 0; i--) {
        buffer.write(integerPart[i]);
        count++;
        if (count == 3 && i > 0) {
          buffer.write(',');
          count = 0;
        }
      }
      integerPart = buffer.toString().split('').reversed.join();
    }

    final formatted = '$integerPart$decimalPart';

    // Calculate new cursor position
    int cursorOffset = newValue.selection.baseOffset;
    // Count commas before cursor in the new formatted string
    int commasInNew = ','.allMatches(formatted.substring(0, cursorOffset.clamp(0, formatted.length))).length;
    // Count commas before cursor in the old value
    int commasInOld = ','.allMatches(oldValue.text.substring(0, oldValue.selection.baseOffset.clamp(0, oldValue.text.length))).length;
    int newCursorPos = cursorOffset + (commasInNew - commasInOld);
    newCursorPos = newCursorPos.clamp(0, formatted.length);

    return TextEditingValue(
      text: formatted,
      selection: TextSelection.collapsed(offset: newCursorPos),
    );
  }
}
