import 'package:didvan/models/tag.dart';
import 'package:didvan/models/view/app_bar_data.dart';
import 'package:didvan/views/home/hashtag/hashtag_state.dart';
import 'package:didvan/views/home/widgets/news_overview.dart';
import 'package:didvan/views/home/widgets/radar_overview.dart';
import 'package:didvan/views/widgets/didvan/scaffold.dart';
import 'package:didvan/views/widgets/state_handlers/sliver_state_handler.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class Hashtag extends StatefulWidget {
  final Tag tag;
  const Hashtag({Key? key, required this.tag}) : super(key: key);

  @override
  _HashtagState createState() => _HashtagState();
}

class _HashtagState extends State<Hashtag> {
  @override
  void initState() {
    final state = context.read<HashtagState>();
    state.id = widget.tag.id;
    Future.delayed(Duration.zero, () => state.getTagItems(page: 1));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return DidvanScaffold(
      appBarData: AppBarData(title: '#' + widget.tag.label, hasBack: true),
      slivers: [
        Consumer<HashtagState>(
          builder: (context, state, child) => SliverStateHandler<HashtagState>(
            itemPadding: const EdgeInsets.only(bottom: 8),
            state: state,
            placeholder: RadarOverview.placeholder,
            builder: (context, state, index) {
              index++;
              if (index % 15 == 0 && index / 15 >= state.page) {
                state.getTagItems(page: index ~/ 15 + 1);
              }
              index--;
              final item = state.items[index];
              final type = item.type;
              if (type == 'radar') {
                return RadarOverview(
                  radar: item,
                  onCommentsChanged: (id, count) => item.comments = count,
                  onMarkChanged: (id, value) => item.marked = value,
                );
              } else if (type == 'news') {
                return NewsOverview(
                  news: item,
                  onMarkChanged: (id, value) => item.marked = value,
                );
              }
              return Container();
            },
            childCount: state.items.length,
            onRetry: () => state.getTagItems(page: 1),
          ),
        )
      ],
    );
  }
}
