import 'package:account_center/common/utils/alert_util.dart';
import 'package:flutter/material.dart';

class CLXSearchBar extends StatefulWidget {
  final ValueChanged<String> onSearch;
  final String placeholder;
  final String defaultValue;
  final bool autofocus;

  const CLXSearchBar({
    super.key,
    this.placeholder = '请输入搜索内容',
    required this.onSearch,
    this.defaultValue = '',
    this.autofocus = false,
  });

  @override
  State<StatefulWidget> createState() {
    return _CLXSearchBar();
  }
}

class _CLXSearchBar extends State<CLXSearchBar> {
  ///编辑控制器
  final TextEditingController _controller = TextEditingController();

  /// 是否显示删除按钮
  bool _hasDeleteIcon = false;

  @override
  void didUpdateWidget(covariant CLXSearchBar oldWidget) {
    if (widget.defaultValue != _controller.text) {
      _controller.value = TextEditingValue(
        text: widget.defaultValue,
        selection: TextSelection.fromPosition(
          TextPosition(
            affinity: TextAffinity.downstream,
            offset: widget.defaultValue.length,
          ),
        ),
      );
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6),
        // color: Color(0xffF2F3F5),
      ),
      child: TextField(
        controller: _controller,
        textInputAction: TextInputAction.search,
        textAlignVertical: TextAlignVertical.center,
        keyboardType: TextInputType.text,
        autofocus: widget.autofocus,
        decoration: InputDecoration(
          filled: true,
          fillColor: Color(0xffF2F3F5),

          /// 输入框decoration属性
          contentPadding:
              const EdgeInsets.symmetric(vertical: 0.0, horizontal: 1.0),

          /// 去掉输入框的边框
          border: const OutlineInputBorder(borderSide: BorderSide.none),

          /// 让文字垂直居中
          isCollapsed: true,

          /// 设置搜索图片
          prefixIcon: const Icon(
            Icons.search,
            color: Color(0xffC5C7D3),
            size: 20,
          ),
          prefixIconConstraints: const BoxConstraints(
            minWidth: 30,
            minHeight: 25,
          ),
          hintText: widget.placeholder,
          hintStyle: const TextStyle(
            fontSize: 15,
            color: Color(0xffC9CDD4),
            fontWeight: FontWeight.w400,
          ),

          /// 设置清除按钮
          suffixIcon: Container(
            padding: EdgeInsetsDirectional.only(
              start: 2.0,
              end: _hasDeleteIcon ? 0.0 : 0,
            ),
            child: _hasDeleteIcon
                ? InkWell(
                    onTap: (() {
                      setState(() {
                        _controller.clear();
                        _hasDeleteIcon = false;
                      });
                    }),
                    child: const Icon(
                      Icons.cancel,
                      size: 18.0,
                      color: Colors.grey,
                    ),
                  )
                : const Text(''),
          ),
        ),
        onChanged: (value) {
          /// 调用父组件中的方法
          widget.onSearch(_controller.text);
          setState(() {
            if (value.isEmpty) {
              _hasDeleteIcon = false;
            } else {
              _hasDeleteIcon = true;
            }
          });
        },
        onEditingComplete: () {
          if (_controller.text.isEmpty) {
            AlertUtil.showCenterToast('搜索内容不能为空');
            return;
          }
          FocusScope.of(context).requestFocus(FocusNode());

          /// 调用父组件中的方法
          widget.onSearch(_controller.text);
        },
      ),
    );
  }

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