import 'package:flutter/material.dart';
import 'package:top_news_app/helper/custom_appbar.dart';
import 'package:top_news_app/helper/sliver_grid_delegate_with_fixed_crossaxiscount_and_fixedheight.dart';
import 'package:top_news_app/localization/localization.dart';
import 'package:top_news_app/providers/article_provider.dart';
import 'package:top_news_app/widget/category_widget.dart';
import '../model/post_category.dart';

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

  @override
  State<CategoriesScreens> createState() => _CategoriesScreensState();
}

class _CategoriesScreensState extends State<CategoriesScreens> {

  late bool _isLoading = true;

  List<PostCategoryData> categories = [];
  List<Widget> widgets = [];

  var articleProvider = ArticleProvider();

  void loadingEffect() async {
    try{
      categories = (await articleProvider.getPostCategories('all'))!;
    } catch (e) {
      rethrow;
    }

    setState(() {
      _isLoading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    loadingEffect();
  }



  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return SafeArea(
      child: Scaffold(
          appBar: customAppBar(getTranslated(context, 'Categories') ?? 'Categories', 'back',context),
          body:  _isLoading
              ? const Center(
            child: CircularProgressIndicator(),
          )
              : ListView(
            children: [
              const SizedBox(
                height: 10,
              ),
              Padding(
                padding: const EdgeInsets.all(8),
                child: GridView.builder(
                  itemCount: categories.length,
                  physics: const NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  gridDelegate:
                  const SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight(
                    crossAxisCount: 2,
                    crossAxisSpacing: 0,
                    height: 180,
                    mainAxisSpacing: 0,
                  ),
                  itemBuilder: (BuildContext context, int index) {
                    return CategoryWidget(
                      fontSize: 24,
                      height: 180,
                        width: (size.width / 2) -6,
                        id: categories[index].id!,
                        name: categories[index].name!,
                        image: categories[index].image!);
                  },
                ),
              )
            ],)),
    );
  }
}


