import 'package:flutter/material.dart';
import 'package:top_news_app/providers/article_provider.dart';
import 'package:top_news_app/screen/category_ways_post_screen.dart';
import 'package:google_fonts/google_fonts.dart';
import '../model/post_category.dart';


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

  @override
  State<CategoryScreen> createState() => _CategoryScreenState();
}

class _CategoryScreenState extends State<CategoryScreen> {

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

  late  bool _isLoading = true;
  var articleProvider = ArticleProvider();

  void loadingEffect() async {
    try{

      categories = (await articleProvider.getPostCategories('all'))!;
      for (var element in categories) {
        categoriesTab.add(Tab(text: '${element.name}'));
        widgets.add(CategoryWaysPostScreen(category: element));
      }
    } catch (e) {
      rethrow;
    }

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

  @override
  void initState() {
    super.initState();
    loadingEffect();
  }
  @override
  Widget build(BuildContext context) {

    return DefaultTabController(
      length: categories.length,
      child: Scaffold(
       extendBody: false,
        appBar: PreferredSize(
          preferredSize:
          Size.fromHeight(MediaQuery.of(context).size.height),
          child: TabBar(
            isScrollable: true,
            labelStyle: GoogleFonts.robotoSerif(
              fontWeight: FontWeight.bold
            ),
            labelColor: Theme.of(context).iconTheme.color,
            tabs: categoriesTab,
          ),

        ),

        body: _isLoading  ? const Center(
          child: CircularProgressIndicator(),
        ) :   TabBarView(
          children: widgets,
        ),
      ),
    );
  }
}

