import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:result_monad/result_monad.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 '../models/connection.dart';
import '../models/exec_error.dart';
import '../models/interaction_type_enum.dart';
import '../routes.dart';
import '../services/connections_manager.dart';
import '../services/interactions_manager.dart';
import '../services/network_status_service.dart';
import '../utils/active_profile_selector.dart';

class InteractionsViewerScreen extends StatelessWidget {
  final String statusId;
  final InteractionType type;

  const InteractionsViewerScreen({
    super.key,
    required this.statusId,
    required this.type,
  });

  List<Connection> getInteractors(InteractionsManager manager) {
    switch (type) {
      case InteractionType.like:
        return manager.getLikes(statusId);
      case InteractionType.reshare:
        return manager.getReshares(statusId);
    }
  }

  FutureResult<List<Connection>, ExecError> refreshInteractors(
      InteractionsManager manager) async {
    switch (type) {
      case InteractionType.like:
        return await manager.updateLikesForStatus(statusId);
      case InteractionType.reshare:
        return await manager.updateResharesForStatus(statusId);
    }
  }

  @override
  Widget build(BuildContext context) {
    final nss = getIt<NetworkStatusService>();
    final manager = context
        .watch<ActiveProfileSelector<InteractionsManager>>()
        .activeEntry
        .value;
    final connections = getInteractors(manager);
    return Scaffold(
      appBar: StandardAppBar.build(context, buildTitle(), actions: [
        StatusAndRefreshButton(
          valueListenable: nss.interactionsLoadingStatus,
          refreshFunction: () async => await refreshInteractors(manager),
          busyColor: Theme.of(context).colorScheme.background,
        )
      ]),
      body: Center(
        child: ResponsiveMaxWidth(
          child: ListView.separated(
            itemCount: connections.length,
            itemBuilder: (context, index) {
              final connection = connections[index];
              return ListTile(
                onTap: () async {
                  await getIt<ActiveProfileSelector<ConnectionsManager>>()
                      .activeEntry
                      .andThenSuccessAsync((cm) async {
                    final existingData = cm.getById(connection.id);
                    if (existingData.isFailure) {
                      await cm.fullRefresh(connection);
                    }
                  });
                  if (context.mounted) {
                    context.pushNamed(ScreenPaths.userProfile,
                        pathParameters: {'id': connection.id});
                  }
                },
                leading: ImageControl(
                  imageUrl: connection.avatarUrl.toString(),
                  iconOverride: const Icon(Icons.person),
                  width: 32.0,
                  onTap: () => context.pushNamed(ScreenPaths.userProfile,
                      pathParameters: {'id': connection.id}),
                ),
                title: Text('${connection.name} (${connection.handle})'),
              );
            },
            separatorBuilder: (_, __) => const Divider(),
          ),
        ),
      ),
    );
  }

  String buildTitle() {
    switch (type) {
      case InteractionType.like:
        return 'Likes';
      case InteractionType.reshare:
        return 'Reshares';
    }
  }
}
