import 'package:flutter/material.dart';

import 'files_search_controller.dart';
import 'files_search_results.dart';

/// Material `SearchDelegate` for the Files module — opens via the magnifier
/// in `FilesPage`'s AppBar (mirroring `SearchMarianumMessages`). Owns one
/// [FilesSearchController]; cache + server hits stream into the result list
/// as the user types.
class FilesSearchDelegate extends SearchDelegate<void> {
  final FilesSearchController _controller;

  FilesSearchDelegate({required List<String> pathScope})
    : _controller = FilesSearchController(initialPathScope: pathScope),
      super(searchFieldLabel: 'Dateien suchen');

  /// Must be called by the host widget after `showSearch` returns so the
  /// controller's listeners and pending debounce timers are released.
  void disposeController() => _controller.dispose();

  @override
  List<Widget>? buildActions(BuildContext context) => [
    if (query.isNotEmpty)
      IconButton(
        tooltip: 'Suche leeren',
        icon: const Icon(Icons.clear),
        onPressed: () {
          query = '';
        },
      ),
  ];

  @override
  Widget? buildLeading(BuildContext context) => IconButton(
    icon: const Icon(Icons.arrow_back),
    tooltip: 'Zurück',
    onPressed: () => close(context, null),
  );

  @override
  Widget buildResults(BuildContext context) {
    _controller.setQuery(query);
    return FilesSearchResults(
      controller: _controller,
      onResultTap: () => close(context, null),
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    _controller.setQuery(query);
    return FilesSearchResults(
      controller: _controller,
      onResultTap: () => close(context, null),
    );
  }
}
