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

import '../../globals.dart';
import '../../models/connection.dart';
import '../../models/timeline_entry.dart';
import '../../models/visibility.dart' as v;
import '../../routes.dart';
import '../../services/auth_service.dart';
import '../../services/connections_manager.dart';
import '../../services/reshared_via_service.dart';
import '../../utils/active_profile_selector.dart';
import '../../utils/dateutils.dart';
import '../image_control.dart';
import '../padding.dart';
import '../visibility_dialog.dart';

class StatusHeaderControl extends StatelessWidget {
  static final _logger = Logger('$StatusHeaderControl');
  final TimelineEntry entry;
  final bool showIsCommentText;

  const StatusHeaderControl({
    super.key,
    required this.entry,
    this.showIsCommentText = false,
  });

  void goToProfile(BuildContext context, String id) {
    context.pushNamed(ScreenPaths.userProfile, pathParameters: {'id': id});
  }

  @override
  Widget build(BuildContext context) {
    late final Connection author;
    late final Connection reshareAuthor;
    final activeProfile = getIt<AccountsService>().currentProfile;
    final reshareId = getIt<ActiveProfileSelector<ReshareViaService>>()
        .getForProfile(activeProfile)
        .transform((s) => s.getForPost(entry.id)?.resharers.firstOrNull)
        .getValueOrElse(() => null);
    final manager = getIt<ActiveProfileSelector<ConnectionsManager>>()
        .getForProfile(activeProfile)
        .fold(
            onSuccess: (m) => m,
            onError: (error) {
              _logger.severe('Error getting connection manager: $error');
              return null;
            });

    author = manager!.getById(entry.authorId).getValueOrElse(
          () => Connection(),
        );
    reshareAuthor = reshareId == null
        ? Connection()
        : manager.getById(reshareId).getValueOrElse(
              () => Connection(),
            );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Wrap(
          crossAxisAlignment: WrapCrossAlignment.end,
          runSpacing: 5.0,
          children: [
            ImageControl(
              imageUrl: author.avatarUrl.toString(),
              iconOverride: const Icon(Icons.person),
              width: 32.0,
              onTap: () => goToProfile(context, author.id),
            ),
            const HorizontalPadding(),
            Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                GestureDetector(
                  onTap: () => goToProfile(context, author.id),
                  child: Text(
                    author.name,
                    style: Theme.of(context).textTheme.bodyLarge,
                  ),
                ),
              ],
            ),
            if (reshareAuthor.isNotEmpty &&
                author.id != activeProfile.userId) ...[
              const HorizontalPadding(width: 3.0),
              const Text('reshared by '),
              const HorizontalPadding(width: 3.0),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ImageControl(
                    imageUrl: reshareAuthor.avatarUrl.toString(),
                    iconOverride: const Icon(Icons.person),
                    width: 32.0,
                    onTap: () => goToProfile(context, reshareAuthor.id),
                  ),
                  const HorizontalPadding(width: 3.0),
                  GestureDetector(
                    onTap: () => goToProfile(context, reshareAuthor.id),
                    child: Text(
                      reshareAuthor.name,
                      style: Theme.of(context).textTheme.bodyLarge,
                    ),
                  ),
                ],
              ),
            ],
            if (showIsCommentText && entry.parentId.isNotEmpty)
              Text(
                ' ...made a comment:',
                style: Theme.of(context).textTheme.bodyLarge,
              ),
          ],
        ),
        Row(
          children: [
            Text(
              ElapsedDateUtils.epochSecondsToString(entry.backdatedTimestamp),
              style: Theme.of(context).textTheme.bodySmall,
            ),
            IconButton(
              onPressed: () async {
                await showVisibilityDialog(context, manager, entry.visibility);
              },
              icon: Icon(
                entry.visibility.type == v.VisibilityType.public
                    ? Icons.public
                    : Icons.lock,
                color: Theme.of(context).hintColor,
                size: Theme.of(context).textTheme.bodySmall?.fontSize,
              ),
            ),
          ],
        ),
      ],
    );
  }
}
