import 'package:flutter/material.dart';
import 'package:top_news_app/helper/custom_appbar.dart';
import 'package:top_news_app/widget/post_widget.dart';
import '../helper/helper.dart';
import '../model/Article.dart';
import '../providers/article_provider.dart';

class CategoryWaysPostListScreen extends StatefulWidget {
  final String id;
  final String title;
  const CategoryWaysPostListScreen({super.key,required this.id, required this.title});

  @override
  State<CategoryWaysPostListScreen> createState() => _CategoryWaysPostListScreenState();
}

class _CategoryWaysPostListScreenState extends State<CategoryWaysPostListScreen> {

  List<ArticleData> feedPosts = [];
  bool _isLoading = true;
  bool isLoadingMore = false;
  int page = 0;
  String param = '';
  final scrollController = ScrollController();
  var articleProvider = ArticleProvider();

  readJson() async {
    await getFeedPosts();
    setState(() {
      _isLoading = false;
    });
  }

  getFeedPosts() async {
    try{
      List<ArticleData> data =
      (await articleProvider.getCategoryPosts(widget.id, page))!;
      //update products
      if (page == 0) {
        feedPosts = data;
      } else {
        feedPosts.addAll(data);
      }
        } catch (e) {
      rethrow;
    }

  }

  @override
  void initState() {
    super.initState();
    scrollController.addListener(_scrollListener);
    page = 0;
    readJson();
  }

  void _scrollListener() async {
    if (scrollController.position.pixels ==
        scrollController.position.maxScrollExtent) {
      setState(() {
        isLoadingMore = true;
      });
      page = page + 1;
      await getFeedPosts();
      setState(() {
        isLoadingMore = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          appBar: customAppBar(widget.title, 'back',context),
          body:  _isLoading
              ? const Center(
            child: CircularProgressIndicator(),
          )
              : ListView(
            controller: scrollController,
            children: [
              PostWidget(posts: feedPosts),
              customSizeBox(10),
              isLoadingMore
                  ? const Center(child: CircularProgressIndicator())
                  : Container(),
              customSizeBox(23),
            ],
          )),
    );
  }
}
