import 'package:flutter/material.dart';
import 'package:top_news_app/localization/localization.dart';
import 'package:top_news_app/model/Article.dart';
import 'package:top_news_app/providers/article_provider.dart';
import 'package:top_news_app/screen/categories_screen.dart';
import 'package:top_news_app/widget/ads_card.dart';
import 'package:top_news_app/widget/carousel_with_indicator.dart';
import 'package:top_news_app/widget/category_widget.dart';
import 'package:top_news_app/widget/polling_card.dart';
import 'package:top_news_app/widget/post_widget.dart';
import '../helper/helper.dart';
import '../model/Ads.dart';
import '../model/Polling.dart';
import '../model/post_category.dart';


class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  List<ArticleData> trendingPosts = [];
  List<ArticleData> feedPosts = [];
  List<ArticleData> brakingPosts = [];
  List<PollingData> polling = [];
  List<PostCategoryData> popularCategories = [];
  List<ArticleData> slider = [];
  List<AdsData> ads = [];
  bool _isLoading = false;
  bool isLoadingMore = true;
  int page = 0;
  String param = '';
  final scrollController = ScrollController();
  var articleProvider = ArticleProvider();

   readJson() async {
     try{
       slider = (await articleProvider.getSliderPosts())!;
       popularCategories = (await articleProvider.getPostCategories('popular'))!;
       brakingPosts = (await articleProvider.getBrakingPosts())!;

       setState(() {
         _isLoading = true;
       });
       polling = (await articleProvider.getRandomPolling('home'))!;

       ads = (await articleProvider.getAds())!;
       trendingPosts = (await articleProvider.getTrendingPosts())!;
       setState(() {

       });
     }catch(e){
       rethrow;
     }

    await getFeedPosts();
  }


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

  setState(() {

  });
  }



  @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 _isLoading
        ? RefreshIndicator(
      onRefresh: () {
        return readJson();
      },

      child: ListView(
        controller: scrollController,
              children: <Widget>[
                customSizeBox(5),
                CarouselWithIndicator(bannerData: slider,),
                customSizeBox(5),
                sectionTitle((){
                },getTranslated(context, 'Braking News') ?? 'Braking News',false,context),
                PostWidget(posts: brakingPosts),
                sectionTitle((){
                  Navigator.push(context, MaterialPageRoute(builder: (context)=>const CategoriesScreens()));
                },getTranslated(context, 'Popular Categories') ?? 'Popular Categories',true,context),
                popularCategories.isEmpty ? Container():  SingleChildScrollView(
                   scrollDirection: Axis.horizontal,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Row(
                      children: [
                 for(int i = 0; i< popularCategories.length; i++)
                         Container(
                             height: 120,
                             width: 120,
                             padding: const EdgeInsets.only(right: 6),
                             child: CategoryWidget(
                               fontSize: 16,
                                 height: 120,
                                 width: 120,
                                 id: popularCategories[i].id ?? 0, name: popularCategories[i].name ?? '', image: popularCategories[i].image ?? '')),
                      ],
                  ),
                    ),
                ),
                polling.isEmpty ? Container() : PollingCard(
                  polling: polling,
                  poll: PollingData(),
                ),
                customSizeBox(10),
                ads.isEmpty ? Container() : AdsCardWidget(data: AdsData(),
                  ads: ads,
                ),
                customSizeBox(10),
                sectionTitle((){
                },getTranslated(context, 'Hot Article') ?? 'Hot Article',false,context),
                trendingPosts.isEmpty ? Container() : PostWidget(posts: trendingPosts,),//8
                customSizeBox(10),
                polling.isEmpty ? Container() : PollingCard(
                  polling: polling,
                  poll: PollingData(),
                ),
                customSizeBox(10),
                ads.isEmpty ? Container() : AdsCardWidget(data: AdsData(),
                  ads: ads,
                ),
                customSizeBox(10),
                feedPosts.isEmpty ? Container() : PostWidget(posts: feedPosts,),//8
                customSizeBox(10),
                ads.isEmpty ? Container() : AdsCardWidget(data: AdsData(),
                  ads: ads,
                ),
                customSizeBox(10),
                isLoadingMore ? const Center(child: CircularProgressIndicator()) : Container(),
                customSizeBox(23),
              ],
            ),
        )
        : const Center(
            child: CircularProgressIndicator(),
          );
  }
}
