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

class AuthorPostScreens extends StatefulWidget {
  final String name;
  final String id;
  final int randomNumber;
  final String image;
  const AuthorPostScreens(
      {super.key,
      required this.name,
      required this.id,
      required this.image,
      required this.randomNumber});

  @override
  State<AuthorPostScreens> createState() => _AuthorPostScreensState();
}

class _AuthorPostScreensState extends State<AuthorPostScreens> {
  bool _isLoading = true;
  List<ArticleData> posts = [];
  AuthorData author = AuthorData();
  String name = '';
  int randomNumber = 0;
  String avatar = '';
  String id = '';
  List<ArticleData> feedPosts = [];
  bool isLoadingMore = false;
  int page = 0;
  String param = '';
  final scrollController = ScrollController();
  var articleProvider = ArticleProvider();

  readJson() async {
    author = await articleProvider.getAuthor(widget.id);
    name = author.name!;
    randomNumber = author.randomNumber!;
    avatar = author.avatar!;
    id = author.id.toString();
    await getFeedPosts();
    setState(() {
      _isLoading = false;
    });
  }

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

  @override
  void initState() {
    super.initState();
    name = widget.name;
    randomNumber = widget.randomNumber;
    avatar = widget.image;
    id = widget.id;
    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: RefreshIndicator(
        onRefresh: () async {
          return await readJson();
        },
        child: Scaffold(
          body: _isLoading
              ? const Center(
                  child: CircularProgressIndicator(),
                )
              : CustomScrollView(
                  controller: scrollController,
                  slivers: [
                    SliverAppBar(
                      pinned: true,
                      backgroundColor: primaryColors.withOpacity(0.4),
                      expandedHeight: 220,
                      flexibleSpace: FlexibleSpaceBar(
                        background: Hero(
                          tag: 'avatar-$randomNumber',
                          child: Container(
                            height: 150,
                            padding: const EdgeInsets.symmetric(
                                horizontal: 20, vertical: 20),
                            decoration: BoxDecoration(
                                image: DecorationImage(
                                    image: NetworkImage(avatar),
                                    fit: BoxFit.cover)),
                          ),
                        ),
                      ),
                      title: Text(name),
                      titleTextStyle: GoogleFonts.robotoCondensed(
                          color: Colors.white,
                          fontSize: 22,
                          fontWeight: FontWeight.w500),
                    ),
                    SliverList(
                        delegate: SliverChildListDelegate([
                      Card(
                        elevation: elevation,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                name,
                                style: GoogleFonts.robotoSerif(
                                    fontSize: 16, fontWeight: FontWeight.w600),
                              ),
                              customSizeBox(4),
                              Text(
                                '${author.bio ?? ''} ',
                                style: GoogleFonts.robotoSerif(
                                    fontSize: 13, fontWeight: FontWeight.w300),
                              ),
                              customSizeBox(8),
                              Wrap(
                                children: [
                                  author.instagramLink != null
                                      ? SocialWidget(
                                          placeholderText: name,
                                          iconData:
                                              SocialIconsFlutter.instagram,
                                          iconColor: Colors.pink,
                                          link: '${author.instagramLink}',
                                          placeholderStyle:
                                              const TextStyle(fontSize: 20),
                                        )
                                      : Container(),
                                  author.twitterLink != null
                                      ? SocialWidget(
                                          placeholderText: name,
                                          iconData: SocialIconsFlutter.twitter,
                                          iconColor: Colors.lightBlue,
                                          link: '${author.twitterLink}',
                                          placeholderStyle:
                                              const TextStyle(fontSize: 20),
                                        )
                                      : Container(),
                                  author.youtubeLink != null
                                      ? SocialWidget(
                                          placeholderText: name,
                                          iconData: SocialIconsFlutter.youtube,
                                          link: '${author.youtubeLink}',
                                          iconColor: Colors.red,
                                          placeholderStyle:
                                              const TextStyle(fontSize: 20),
                                        )
                                      : Container(),
                                  author.linkdinLink != null
                                      ? SocialWidget(
                                          placeholderText: name,
                                          iconData:
                                              SocialIconsFlutter.linkedin_box,
                                          link: '${author.linkdinLink}',
                                          iconColor: Colors.blueGrey,
                                          placeholderStyle:
                                              const TextStyle(fontSize: 20),
                                        )
                                      : Container(),
                                  author.facebookLink != null
                                      ? SocialWidget(
                                          placeholderText: name,
                                          iconData:
                                              SocialIconsFlutter.facebook_box,
                                          link: '${author.facebookLink}',
                                          iconColor: Colors.blueGrey,
                                          placeholderStyle:
                                              const TextStyle(fontSize: 20),
                                        )
                                      : Container(),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      customSizeBox(6),
                      PostWidget(posts: feedPosts),
                      customSizeBox(10),
                      isLoadingMore
                          ? const Center(child: CircularProgressIndicator())
                          : Container(),
                      customSizeBox(30),
                    ])),
                  ],
                ),
        ),
      ),
    );
  }
}
