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

import '../../models/entry_tree_item.dart';
import '../../models/flattened_tree_item.dart';
import '../../models/timeline_entry.dart';
import '../../services/timeline_manager.dart';
import '../../utils/active_profile_selector.dart';
import '../../utils/entry_tree_item_flattening.dart';
import 'flattened_tree_entry_control.dart';

class PostControl extends StatefulWidget {
  final EntryTreeItem originalItem;
  final String scrollToId;
  final bool openRemote;
  final bool showStatusOpenButton;
  final bool isRoot;

  const PostControl({
    super.key,
    required this.originalItem,
    required this.scrollToId,
    required this.openRemote,
    required this.showStatusOpenButton,
    required this.isRoot,
  });

  @override
  State<PostControl> createState() => _PostControlState();
}

class _PostControlState extends State<PostControl> {
  static final _logger = Logger('$PostControl');

  final ItemScrollController itemScrollController = ItemScrollController();
  final ItemPositionsListener itemPositionsListener =
      ItemPositionsListener.create();

  var showContent = true;

  EntryTreeItem get item => widget.originalItem;

  TimelineEntry get entry => item.entry;

  @override
  void initState() {
    super.initState();
    showContent = entry.spoilerText.isEmpty;
  }

  @override
  Widget build(BuildContext context) {
    context.watch<ActiveProfileSelector<TimelineManager>>();
    _logger.finest('Building ${item.entry.toShortString()}');
    if (!widget.isRoot) {
      return FlattenedTreeEntryControl(
        originalItem: item.flatten(topLevelOnly: true).first,
        openRemote: widget.openRemote,
        showStatusOpenButton: widget.showStatusOpenButton,
      );
    }

    final items = widget.originalItem.flatten();
    return buildListView(context, items);
  }

  Widget buildListView(
    BuildContext context,
    List<FlattenedTreeItem> items,
  ) {
    final int count = items.length;
    final int scrollToIndex = _scrollToIndexCalc(items);

    // TODO Figure out why doesn't scroll to correct position on loading
    _logger.finest('Building view with initial position at $scrollToIndex');

    return ScrollablePositionedList.builder(
        physics: const AlwaysScrollableScrollPhysics(),
        itemCount: count,
        initialScrollIndex: scrollToIndex,
        itemScrollController: itemScrollController,
        itemPositionsListener: itemPositionsListener,
        itemBuilder: (context, index) {
          return FlattenedTreeEntryControl(
            originalItem: items[index],
            openRemote: widget.openRemote,
            showStatusOpenButton: widget.showStatusOpenButton,
          );
        });
  }

  int _scrollToIndexCalc(List<FlattenedTreeItem> items) {
    final scrollToIndexCalc = items.indexWhere(
      (e) => e.timelineEntry.id == widget.scrollToId,
    );
    if (scrollToIndexCalc < 0) {
      return 0;
    }

    return scrollToIndexCalc;
  }
}
