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

import '../controls/linear_status_indicator.dart';
import '../controls/responsive_max_width.dart' show ResponsiveMaxWidth;
import '../controls/standard_appbar.dart';
import '../controls/timeline/post_control.dart';
import '../globals.dart';
import '../services/network_status_service.dart';
import '../services/timeline_manager.dart';
import '../utils/active_profile_selector.dart';

class PostScreen extends StatefulWidget {
  final String id;

  final String goToId;

  const PostScreen({
    super.key,
    required this.id,
    required this.goToId,
  });

  @override
  State<PostScreen> createState() => _PostScreenState();
}

class _PostScreenState extends State<PostScreen> {
  bool firstDraw = true;

  @override
  void initState() {
    Future.delayed(const Duration(milliseconds: 500), () async {
      getIt<ActiveProfileSelector<TimelineManager>>()
          .activeEntry
          .andThenSuccess(
            (m) => m.refreshStatusChain(widget.id),
          );
    });
  }

  @override
  Widget build(BuildContext context) {
    final nss = getIt<NetworkStatusService>();
    final manager = context
        .watch<ActiveProfileSelector<TimelineManager>>()
        .activeEntry
        .value;
    final body = manager.getPostTreeEntryBy(widget.id).fold(
        onSuccess: (post) => RefreshIndicator(
              onRefresh: () async {
                manager.refreshStatusChain(widget.id);
                return;
              },
              child: PostControl(
                originalItem: post,
                scrollToId: widget.goToId,
                openRemote: true,
                showStatusOpenButton: false,
                isRoot: true,
              ),
            ),
        onError: (error) => Text(firstDraw || nss.timelineLoadingStatus.value
            ? 'Attempting to load post'
            : 'Error getting post: $error'));
    firstDraw = true;
    return Scaffold(
        appBar: StandardAppBar.build(context, 'View Post', actions: []),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              StandardLinearProgressIndicator(nss.timelineLoadingStatus),
              Expanded(child: ResponsiveMaxWidth(child: body)),
            ],
          ),
        ));
  }
}
