import 'package:flutter/material.dart';

import '../../../../state/app/infrastructure/loadable_state/view/loadable_state_consumer.dart';
import '../../../../state/app/modules/timetable/bloc/timetable_bloc.dart';
import '../../../../state/app/modules/timetable/bloc/timetable_state.dart';
import '../../../../widget/placeholder_view.dart';
import 'subject_color_filter.dart';
import 'subject_color_tile.dart';

/// AppBar-Suche für die Fach-Farben (gleiches Muster wie die übrigen Bereiche).
/// Über [BlocBuilder] reaktiv, damit sich Farbe/Sortierung nach einer Änderung
/// sofort aktualisieren.
class SearchSubjectColors extends SearchDelegate<void> {
  @override
  List<Widget>? buildActions(BuildContext context) => [
    if (query.isNotEmpty)
      IconButton(
        onPressed: () => query = '',
        tooltip: 'Leeren',
        icon: const Icon(Icons.clear),
      ),
  ];

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

  @override
  Widget buildResults(BuildContext context) => _results(context);

  @override
  Widget buildSuggestions(BuildContext context) => _results(context);

  Widget _results(BuildContext context) {
    return LoadableStateConsumer<TimetableBloc, TimetableState>(
      child: (state, _) {
        final relevant = filterAndSortSubjects(
          state.subjects?.result ?? const [],
          planSubjectShortNames(state),
        );
        final matches = searchSubjects(relevant, query);
        if (matches.isEmpty) {
          return const PlaceholderView(
            icon: Icons.search_off_outlined,
            text: 'Keine Treffer',
          );
        }
        return ListView.builder(
          itemCount: matches.length,
          itemBuilder: (_, index) => SubjectColorTile(matches[index]),
        );
      },
    );
  }
}
