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

import '../../../api/marianumcloud/autocomplete/autocompleteApi.dart';
import '../../../api/marianumcloud/autocomplete/autocompleteResponse.dart';
import '../../../model/endpointData.dart';
import '../../../widget/placeholderView.dart';

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

  @override
  List<Widget>? buildActions(BuildContext context) {
    return [
      if(future != null && query.isNotEmpty) FutureBuilder(
        future: future!.value,
        builder: (context, snapshot) {
          if(snapshot.connectionState != ConnectionState.done) {
            return Container(
              padding: const EdgeInsets.all(10),
              child: const Center(
                child: SizedBox(
                  height: 20,
                  width: 20,
                  child: CircularProgressIndicator(
                    strokeWidth: 3,
                  ),
                ),
              ),
            );
          }
          return const SizedBox.shrink();
        },
      ),
      if(query.isNotEmpty) IconButton(onPressed: () => query = "", icon: const Icon(Icons.delete)),
    ];
  }

  @override
  Widget? buildLeading(BuildContext context) {
    return null;
  }

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

    if(query.isEmpty) {
      return const PlaceholderView(
        text: "Suche nach benutzern",
        icon: Icons.person_search_outlined,
      );
    }

    future = CancelableOperation.fromFuture(AutocompleteApi().find(query));
    return FutureBuilder<AutocompleteResponse>(
      future: future!.value,
      builder: (context, snapshot) {
        if(snapshot.hasData) {
          return ListView.builder(
            itemCount: snapshot.data!.data.length,
            itemBuilder: (context, index) {
              AutocompleteResponseObject object = snapshot.data!.data[index];
              CircleAvatar circleAvatar = CircleAvatar(
                foregroundImage: Image.network("https://${EndpointData().nextcloud().full()}/avatar/${object.id}/128").image,
                backgroundColor: Theme.of(context).primaryColor,
                foregroundColor: Colors.white,
                child: const Icon(Icons.person),
              );
              return ListTile(
                leading: circleAvatar,
                title: Text(object.label),
                subtitle: Text(object.id),
                trailing: const Icon(Icons.arrow_right),
                onTap: () {
                  close(context, object.id);
                },
              );
            }
          );
        } else if(snapshot.hasError) {
          return const PlaceholderView(icon: Icons.search_off, text: "Ein fehler ist aufgetreten. Bist du mit dem Internet verbunden?");
        }

        return const Center(child: CircularProgressIndicator());
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return buildResults(context);
  }

}