import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';

class KwTextInput extends StatefulWidget {
  final TextEditingController? controller;
  final void Function(String)? onChanged;
  final void Function(String)? onFieldSubmitted;
  final String? title;
  final String? hintText;
  final String? helperText;
  final bool obscureText;
  final bool enabled;
  final bool readOnly;
  final bool showError;
  final TextInputType? keyboardType;
  final List<TextInputFormatter>? inputFormatters;
  final bool showCounter;
  final FocusNode? focusNode;
  final TextInputAction? textInputAction;
  final double minHeight;
  final TextStyle? textStyle;
  final Widget? suffixIcon;
  final int? minLines;
  final int? maxLines;
  final int? maxLength;
  final double radius;
  final Color? borderColor;
  final Null Function(bool hasFocus)? onFocusChanged;

  const KwTextInput({
    super.key,
    required this.controller,
    this.title,
    this.onChanged,
    this.onFieldSubmitted,
    this.hintText,
    this.helperText,
    this.minHeight = standardHeight,
    this.suffixIcon,
    this.obscureText = false,
    this.showError = false,
    this.enabled = true,
    this.readOnly = false,
    this.keyboardType,
    this.inputFormatters,
    this.showCounter = false,
    this.focusNode,
    this.textInputAction,
    this.textStyle,
    this.maxLength,
    this.minLines,
    this.maxLines,
    this.radius = 12,
    this.borderColor,
    this.onFocusChanged,
  });

  static const standardHeight = 48.0;

  @override
  State<KwTextInput> createState() => _KwTextInputState();
}

class _KwTextInputState extends State<KwTextInput> {
  late FocusNode _focusNode;

  @override
  initState() {
    _focusNode = widget.focusNode ?? FocusNode();
    _focusNode.addListener(() {
      setState(() {});
      widget.onFocusChanged?.call(_focusNode.hasFocus);
    });
    super.initState();
  }

  Color _helperTextColor() {
    if (widget.showError) {
      return AppColors.statusError;
    } else {
      if (!widget.enabled) {
        return AppColors.grayDisable;
      }
      return AppColors.bgColorDark;
    }
  }

  Color _borderColor() {
    if (!widget.enabled) {
      return AppColors.grayDisable;
    }

    if (widget.showError ||
        widget.maxLength != null &&
            (widget.controller?.text.length ?? 0) > widget.maxLength!) {
      return AppColors.statusError;
    }

    if (_focusNode.hasFocus) {
      return AppColors.bgColorDark;
    }

    return widget.borderColor ?? AppColors.grayStroke;
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (widget.title != null)
            Padding(
              padding: const EdgeInsets.only(left: 16),
              child: Text(
                widget.title!,
                style: AppTextStyles.bodyTinyReg.copyWith(
                  color: widget.enabled
                      ? AppColors.blackGray
                      : AppColors.grayDisable,
                ),
              ),
            ),
          if (widget.title != null) const SizedBox(height: 4),
          GestureDetector(
            onTap: () {
              if (widget.enabled && !widget.readOnly) {
                _focusNode.requestFocus();
              }
            },
            child: Stack(
              children: [
                Container(
                  padding: EdgeInsets.only(bottom: widget.showCounter ? 24 : 0),
                  alignment: Alignment.topCenter,
                  constraints: BoxConstraints(
                    minHeight: widget.minHeight,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    borderRadius: BorderRadius.all(Radius.circular(
                        widget.minHeight > KwTextInput.standardHeight
                            ? widget.radius
                            : widget.minHeight / 2)),
                    border: Border.all(
                      color: _borderColor(),
                    ),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: TextFormField(
                          focusNode: _focusNode,
                          inputFormatters: widget.inputFormatters,
                          keyboardType: widget.keyboardType,
                          enabled: widget.enabled && !widget.readOnly,
                          controller: widget.controller,
                          obscureText: widget.obscureText,
                          maxLines: widget.maxLines,
                          minLines: widget.minLines ?? 1,
                          maxLength: widget.maxLength,
                          onChanged: widget.onChanged,
                          textInputAction: widget.textInputAction,
                          onFieldSubmitted: widget.onFieldSubmitted,
                          onTapOutside: (_) {
                            _focusNode.unfocus();
                          },
                          style: widget.textStyle ??
                              AppTextStyles.bodyMediumReg.copyWith(
                                color: !widget.enabled
                                    ? AppColors.grayDisable
                                    : null,
                              ),
                          decoration: InputDecoration(
                            counter: const SizedBox.shrink(),
                            fillColor: Colors.transparent,
                            contentPadding: const EdgeInsets.symmetric(
                                horizontal: 16, vertical: 8),
                            hintText: widget.hintText,
                            // errorStyle: p2pTextStyles.paragraphSmall(
                            //     color: p2pColors.borderDanger),
                            hintStyle: widget.textStyle ??
                                AppTextStyles.bodyMediumReg.copyWith(
                                  color: widget.enabled
                                      ? AppColors.blackGray
                                      : AppColors.grayDisable,
                                ),
                            border: InputBorder.none,
                          ),
                        ),
                      ),
                      if (widget.suffixIcon != null)
                        SizedBox(
                          child: widget.suffixIcon!,
                        ),
                    ],
                  ),
                ),
                if (widget.showCounter)
                  Positioned(
                    bottom: 12,
                    left: 12,
                    child: Text(
                      '${widget.controller?.text.length}/'
                      '${(widget.maxLength ?? 0)}',
                      style: AppTextStyles.bodySmallReg.copyWith(
                          color: (widget.controller?.text.length ?? 0) >
                                  (widget.maxLength ?? 0)
                              ? AppColors.statusError
                              : AppColors.blackGray),
                    ),
                  ),
                if (widget.minHeight > KwTextInput.standardHeight)
                  Positioned(
                    bottom: 12,
                    right: 12,
                    child: Assets.images.icons.textFieldNotches.svg(
                      height: 12,
                      width: 12,
                    ),
                  ),
              ],
            ),
          ),
          if (widget.helperText != null &&
              (widget.helperText?.isNotEmpty ?? false)) ...[
            const SizedBox(height: 4),
            Row(
              children: [
                const Gap(16),
                Text(
                  widget.helperText!,
                  style: AppTextStyles.bodyTinyReg.copyWith(
                    height: 1,
                    color: _helperTextColor(),
                  ),
                ),
              ],
            )
          ]
        ],
      ),
    );
  }
}
