// ignore_for_file: must_be_immutable

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';

class InputTextField extends StatefulWidget {
  InputTextField({
    super.key,
    this.label = "Label",
    this.hintText = "",
    this.intialValue = "",
    this.editable = true,
    this.onChanged,
    this.bgColor = Colors.transparent,
    this.bgColorOnHover = LabColors.base300,
    this.hideTextLine = false,
    this.singleLine = false,
    this.maxLines,
    this.maxLength,
  });

  final String label;
  final String hintText;
  final String intialValue;
  final bool editable;
  final ValueChanged<String>? onChanged;
  final TextEditingController controller = TextEditingController();
  final FocusNode focusNode = FocusNode();
  final Color bgColor;
  final Color bgColorOnHover;
  final bool hideTextLine;
  final bool singleLine;
  int? maxLines = 1;
  int? maxLength;

  @override
  State<InputTextField> createState() => _InputTextFieldState();
}

class _InputTextFieldState extends State<InputTextField> {
  bool _isHover = false;
  int _currentLength = 0;

  @override
  void initState() {
    super.initState();
    widget.controller.text = widget.intialValue;
    widget.controller.addListener(_updateLength);
  }

  @override
  void dispose() {
    widget.controller.dispose();
    super.dispose();
  }

  void _updateLength() {
    setState(() {
      _currentLength = widget.controller.text.length;
    });
  }

  @override
  void didUpdateWidget(covariant InputTextField oldWidget) {
    widget.controller.text = widget.intialValue;
    if (!widget.focusNode.hasFocus) {
      widget.controller.selection = TextSelection.fromPosition(TextPosition(
        offset: widget.controller.text.length,
      ));
    }
    setState(() {});
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: GestureDetector(
        onTap: _handleTap,
        child: MouseRegion(
          cursor: SystemMouseCursors.text,
          onEnter: _handleMouseEnter,
          onExit: _handleMouseExit,
          child: Container(
            padding: EdgeInsets.all(5),
            decoration: BoxDecoration(
              color: _isHover ? widget.bgColorOnHover : widget.bgColor,
              borderRadius: BorderRadius.circular(5),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  widget.label,
                  style: TextStyle(
                    fontSize: 14,
                    color: LabColors.text600,
                  ),
                ),
                SizedBox(height: 2),
                TextField(
                  decoration: null,
                  controller: widget.controller,
                  focusNode: widget.focusNode,
                  maxLines: widget.maxLines,
                  maxLength: widget.maxLength,
                  inputFormatters: [
                    if (widget.maxLength != null) ...[
                      LengthLimitingTextInputFormatter(widget.maxLength)
                    ],
                    if (widget.singleLine) ...[
                      FilteringTextInputFormatter.deny(RegExp(r"\n|\r")),
                    ],
                  ],
                  style: TextStyle(
                    fontSize: 18,
                    color: LabColors.text800,
                  ),
                  enabled: widget.editable,
                  onChanged: widget.onChanged,
                ),
                Container(
                  height: 2,
                  color: LabColors.base600,
                ),
                _buildTextLength(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTextLength() {
    if (widget.maxLength != null && !widget.hideTextLine)
      return Container(
        alignment: Alignment.topRight,
        margin: EdgeInsets.only(top: 10),
        child: Text(
          '$_currentLength/${widget.maxLength}',
          style: TextStyle(
            fontSize: 18,
            color: LabColors.text800,
          ),
        ),
      );
    return SizedBox();
  }

  void _handleMouseEnter(PointerEvent details) {
    setState(() {
      _isHover = true;
    });
  }

  void _handleMouseExit(PointerEvent details) {
    setState(() {
      _isHover = false;
    });
  }

  // 如果没聚焦，点击后聚焦
  void _handleTap() {
    if (!widget.focusNode.hasFocus) {
      widget.focusNode.requestFocus();
    }
  }
}
