import 'package:flutter/material.dart';

import '../../../state/app/modules/marianum_dates/bloc/marianum_dates_state.dart';
import '../../../widget/placeholder_view.dart';
import 'widgets/event_list_tile.dart';

class SearchMarianumDates extends SearchDelegate<MarianumDate?> {
  final List<MarianumDate> events;

  SearchMarianumDates(this.events);

  List<MarianumDate> _matches() {
    if (query.trim().isEmpty) return events;
    final q = query.trim().toLowerCase();
    return events.where((e) {
      final title = e.title.toLowerCase();
      final desc = e.description?.toLowerCase() ?? '';
      return title.contains(q) || desc.contains(q);
    }).toList();
  }

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

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

  @override
  Widget buildResults(BuildContext context) {
    final matches = _matches();
    if (matches.isEmpty) {
      return const PlaceholderView(
        icon: Icons.search_off_outlined,
        text: 'Keine Treffer',
      );
    }
    return ListView.builder(
      itemCount: matches.length,
      itemBuilder: (_, i) => MarianumDateRow(event: matches[i]),
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) => buildResults(context);
}
