import 'package:flutter/material.dart';

import '../../../routing/app_routes.dart';
import '../../../state/app/modules/marianum_message/bloc/marianum_message_state.dart';
import '../../../widget/centered_leading.dart';
import '../../../widget/placeholder_view.dart';

class SearchMarianumMessages extends SearchDelegate<MarianumMessage?> {
  final String base;
  final List<MarianumMessage> messages;

  SearchMarianumMessages({required this.base, required this.messages});

  List<MarianumMessage> _matches() {
    final q = query.trim().toLowerCase();
    if (q.isEmpty) return messages;
    return messages.where((m) {
      return m.name.toLowerCase().contains(q) ||
          m.date.toLowerCase().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) {
        final message = matches[i];
        return ListTile(
          leading: const CenteredLeading(Icon(Icons.newspaper)),
          title: Text(message.name, overflow: TextOverflow.ellipsis),
          subtitle: Text('vom ${message.date}'),
          trailing: const Icon(Icons.arrow_right),
          onTap: () {
            close(context, message);
            AppRoutes.openMarianumMessage(context, message);
          },
        );
      },
    );
  }

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