import 'package:async/async.dart';
import 'package:flutter/material.dart';

import '../../../api/errors/error_mapper.dart';
import '../../../api/marianumconnect/queries/user_search/user_search.dart';
import '../../../api/marianumconnect/queries/user_search/user_search_response.dart';
import '../../../widget/app_progress_indicator.dart';
import '../../../widget/placeholder_view.dart';
import 'widgets/user_search_tile.dart';

class JoinChat extends SearchDelegate<String> {
  CancelableOperation<UserSearchResponse>? future;

  @override
  List<Widget>? buildActions(BuildContext context) => [
    if (future != null && query.isNotEmpty)
      FutureBuilder(
        future: future!.value,
        builder: (context, snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            return const Padding(
              padding: EdgeInsets.all(10),
              child: Center(child: AppProgressIndicator.medium()),
            );
          }
          return const SizedBox.shrink();
        },
      ),
    if (query.isNotEmpty)
      IconButton(
        tooltip: 'Leeren',
        onPressed: () => query = '',
        icon: const Icon(Icons.clear),
      ),
  ];

  @override
  Widget? buildLeading(BuildContext context) => null;

  @override
  Widget buildResults(BuildContext context) {
    if (future != null) future!.cancel();

    if (query.isEmpty) {
      return const PlaceholderView(
        text: 'Suche nach Schülerinnen, Schülern und Lehrkräften',
        icon: Icons.person_search_outlined,
      );
    }

    future = CancelableOperation.fromFuture(UserSearch().run(query));
    return FutureBuilder<UserSearchResponse>(
      future: future!.value,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          final results = snapshot.data!.result;
          if (results.isEmpty) {
            return PlaceholderView(
              icon: Icons.person_off_outlined,
              text: 'Keine Treffer für „$query"',
            );
          }
          return ListView.builder(
            itemCount: results.length,
            itemBuilder: (context, index) {
              final object = results[index];
              return UserSearchTile(
                user: object,
                onTap: () => close(context, object.username),
              );
            },
          );
        } else if (snapshot.hasError) {
          return PlaceholderView(
            icon: Icons.search_off,
            text: errorToUserMessage(snapshot.error),
          );
        }

        return const Center(child: AppProgressIndicator.large());
      },
    );
  }

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