import 'package:flutter/material.dart';
import 'package:recording_tool/core/utils/rate_limiter.dart';

class AppSearchBar extends StatefulWidget {
  const AppSearchBar({
    super.key,
    this.hint = '搜索',
    this.onChanged,
    this.onSubmitted,
    this.debounceDuration = const Duration(milliseconds: 300),
  });

  final String hint;
  final ValueChanged<String>? onChanged;
  final ValueChanged<String>? onSubmitted;
  final Duration debounceDuration;

  @override
  State<AppSearchBar> createState() => _AppSearchBarState();
}

class _AppSearchBarState extends State<AppSearchBar> {
  final _controller = TextEditingController();
  final _rateLimit = RateLimitHub();

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

  @override
  Widget build(BuildContext context) {
    return SearchBar(
      controller: _controller,
      hintText: widget.hint,
      leading: const Icon(Icons.search),
      trailing: [
        if (_controller.text.isNotEmpty)
          IconButton(
            tooltip: '清除',
            onPressed: () {
              setState(_controller.clear);
              widget.onChanged?.call('');
            },
            icon: const Icon(Icons.close),
          ),
      ],
      onChanged: (value) {
        setState(() {});
        _rateLimit.debounce<String>(
          key: 'search',
          value: value,
          duration: widget.debounceDuration,
          onCallback: (text) => widget.onChanged?.call(text),
        );
      },
      onSubmitted: widget.onSubmitted,
    );
  }
}
