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

import '../../models/TimelineIdentifiers.dart';
import '../../services/timeline_manager.dart';
import '../../utils/active_profile_selector.dart';
import 'post_control.dart';

class TimelinePanel extends StatelessWidget {
  static final _logger = Logger('$TimelinePanel');
  final TimelineIdentifiers timeline;
  final controller = ItemScrollController();

  TimelinePanel({super.key, required this.timeline});

  Future<void> update(BuildContext context, TimelineManager manager) async {
    final confirm =
        await showYesNoDialog(context, 'Reload timeline from scratch?');
    if (confirm == true) {
      await manager.updateTimeline(
        timeline,
        TimelineRefreshType.refresh,
      );
    }
  }

  void scrollToTop() {
    controller.jumpTo(index: 0);
  }

  @override
  Widget build(BuildContext context) {
    _logger.finer('Build');
    final manager = context
        .watch<ActiveProfileSelector<TimelineManager>>()
        .activeEntry
        .value;
    final items = manager.getTimeline(timeline);
    return RefreshIndicator(
      onRefresh: () async {
        update(context, manager);
        return;
      },
      child: items.isEmpty
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ElevatedButton(
                      onPressed: () => manager.updateTimeline(
                          timeline, TimelineRefreshType.refresh),
                      child: const Text('Load Posts'))
                ],
              ),
            )
          : ScrollablePositionedList.builder(
              itemScrollController: controller,
              physics: const AlwaysScrollableScrollPhysics(),
              itemBuilder: (context, index) {
                if (index == 0) {
                  return TextButton(
                      onPressed: () async => await manager.updateTimeline(
                          timeline, TimelineRefreshType.loadNewer),
                      child: const Text('Load newer posts'));
                }

                if (index == items.length + 1) {
                  return TextButton(
                      onPressed: () async => await manager.updateTimeline(
                          timeline, TimelineRefreshType.loadOlder),
                      child: const Text('Load older posts'));
                }
                final itemIndex = index - 1;
                final item = items[itemIndex];
                TimelinePanel._logger.finest(
                    'Building item: $itemIndex: ${item.entry.toShortString()}');
                return PostControl(
                  originalItem: item,
                  scrollToId: item.id,
                  openRemote: false,
                  showStatusOpenButton: true,
                  isRoot: false,
                );
              },
              itemCount: items.length + 2,
            ),
    );
  }
}
