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

import '../../globals.dart';
import '../../models/connection.dart';
import '../../services/connections_manager.dart';
import '../../utils/active_profile_selector.dart';
import '../image_control.dart';

class MentionAutocompleteOptions extends StatelessWidget {
  static final _logger = Logger('$MentionAutocompleteOptions');

  const MentionAutocompleteOptions({
    super.key,
    required this.query,
    required this.onMentionUserTap,
  });

  final String query;
  final ValueSetter<Connection> onMentionUserTap;

  @override
  Widget build(BuildContext context) {
    final users = getIt<ActiveProfileSelector<ConnectionsManager>>()
        .activeEntry
        .andThenSuccess((manager) => manager.getKnownUsersByName(query))
        .fold(
            onSuccess: (users) => users,
            onError: (error) {
              _logger.severe('Error getting users list: $error');
              return [];
            });

    if (users.isEmpty) return const SizedBox.shrink();

    return Card(
      margin: const EdgeInsets.all(8),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      clipBehavior: Clip.hardEdge,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            color: const Color(0xFFF7F7F8),
            child: ListTile(
              dense: true,
              horizontalTitleGap: 0,
              title: Text("Users matching '$query'"),
            ),
          ),
          LimitedBox(
            maxHeight: MediaQuery.of(context).size.height * 0.2,
            child: ListView.separated(
              padding: EdgeInsets.zero,
              shrinkWrap: true,
              itemCount: users.length,
              separatorBuilder: (_, __) => const Divider(height: 0),
              itemBuilder: (context, i) {
                final user = users.elementAt(i);
                return ListTile(
                    dense: true,
                    leading: ImageControl(
                      imageUrl: user.avatarUrl.toString(),
                      iconOverride: const Icon(Icons.person),
                      width: 25,
                      height: 25,
                      onTap: () => onMentionUserTap(user),
                    ),
                    title: Text(user.name),
                    subtitle: Text('@${user.handle}'),
                    onTap: () {
                      onMentionUserTap(user);
                    });
              },
            ),
          ),
        ],
      ),
    );
  }
}
