import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../controls/image_control.dart';
import '../controls/responsive_max_width.dart';
import '../controls/standard_appbar.dart';
import '../controls/status_and_refresh_button.dart';
import '../globals.dart';
import '../routes.dart';
import '../services/direct_message_service.dart';
import '../services/network_status_service.dart';
import '../utils/active_profile_selector.dart';
import '../utils/dateutils.dart';

class MessagesScreen extends StatelessWidget {
  const MessagesScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final service = context
        .watch<ActiveProfileSelector<DirectMessageService>>()
        .activeEntry
        .value;
    final nss = getIt<NetworkStatusService>();
    return Scaffold(
      appBar: StandardAppBar.build(context, 'Direct Message Threads', actions: [
        StatusAndRefreshButton(
          valueListenable: nss.directMessageUpdateStatus,
          refreshFunction: () async => await service.updateThreads(),
          busyColor: Theme.of(context).colorScheme.background,
        ),
        IconButton(
          onPressed: () {
            context.push('/messages/new_thread');
          },
          icon: const Icon(Icons.add),
        )
      ]),
      body: RefreshIndicator(
        onRefresh: () async {
          service.updateThreads();
        },
        child: Center(child: buildBody(context, service)),
      ),
    );
  }

  Widget buildBody(BuildContext context, DirectMessageService service) {
    final threads = service.getThreads();
    threads.sort((t1, t2) =>
        t2.messages.last.createdAt.compareTo(t1.messages.last.createdAt));
    return threads.isEmpty
        ? const Text('No Direct Message Threads')
        : ResponsiveMaxWidth(
            child: ListView.separated(
              itemCount: threads.length,
              itemBuilder: (context, index) {
                final thread = threads[index];
                final style = thread.allSeen
                    ? null
                    : const TextStyle(fontWeight: FontWeight.bold);
                return ListTile(
                  onTap: () => context.pushNamed(
                    ScreenPaths.thread,
                    queryParameters: {'uri': thread.parentUri},
                  ),
                  leading: ImageControl(
                    imageUrl: thread.participants.first.avatarUrl.toString(),
                    iconOverride: const Icon(Icons.person),
                    width: 32.0,
                    onTap: null,
                  ),
                  title: Text(
                    [
                      'You',
                      ...thread.participants
                          .map((p) => '${p.name}(${p.handle})')
                    ].join(thread.participants.length == 1 ? ' & ' : ', '),
                    softWrap: true,
                    style: style,
                  ),
                  subtitle: Text(
                    thread.title,
                    style: style,
                  ),
                  trailing: Text(
                    ElapsedDateUtils.epochSecondsToString(
                        thread.messages.last.createdAt),
                    style: style,
                  ),
                );
              },
              separatorBuilder: (_, __) => const Divider(),
            ),
          );
  }
}
