
import 'package:flutter/material.dart';
import 'package:top_news_app/helper/helper.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/author_post_screens.dart';
import 'package:top_news_app/screen/category_ways_post_list_screen.dart';
import 'package:top_news_app/screen/comments_screen.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:top_news_app/widget/post_details_widget.dart';
import 'package:top_news_app/widget/post_widget.dart';

import '../services/storage_service.dart';

class NewsDetailsScreen extends StatefulWidget {
  final ArticleData data;
  const NewsDetailsScreen({super.key, required this.data});

  @override
  State<NewsDetailsScreen> createState() => _NewsDetailsScreenState();
}

class _NewsDetailsScreenState extends State<NewsDetailsScreen> {

  bool _isLoading = true;
  
  List<ArticleData> relatedPost = [];
  ArticleData postDetails = ArticleData();
  var articleProvider = ArticleProvider();
  late String categoriesId;
  bool isAuth = false;
  var storage = StorageService();
  bool isBookMark = false;


  bookMark() {
    if(!isAuth){
      dialogLogin(context);
    }else{
      storeBookMark();
    }

  }

  storeBookMark() async{
    isBookMark =  await articleProvider.bookMarking(postDetails.postId);
    setState(() {

    });
  }

  checkAuth() async {
    isAuth = (await storage.isAuthInLocal())!;
    setState(() {
      isBookMark = postDetails.bookmark!;
    });
  }


  refreshPost() async{
    try{
      postDetails = await articleProvider.getPostDetails(postDetails.postId);
    }catch(e){
      rethrow;
    }

    await getRelatedPost();
  }

  getRelatedPost() async{
    try{
      relatedPost = (await articleProvider.getRelatedPost(categoriesId))!;
    }catch(e){
      rethrow;
    }

    setState(() {

    });
  }




  Future<void> readJson() async {
    postDetails = widget.data;
    categoriesId = widget.data.categoriesId?[0] ?? '1';
    await articleProvider.views(widget.data.postId);

    Future.delayed(const Duration(seconds: 1), () {
      setState(() {
        _isLoading = false;
      });
    });

    
    //get related post
    await getRelatedPost();
   
  }
  @override
  void initState() {
    
    super.initState();
    readJson();
    checkAuth();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return SafeArea(
      child: RefreshIndicator(
        onRefresh: () async {
          return await refreshPost();
        },
        child: Scaffold(
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          body:  ListView(
            children: [
              SizedBox(
                height:size.height / 1.8,
                child: Stack(
                  children: [
                    Hero(
                      tag: 'post-${postDetails.randomNumber}',
                      child: Container(
                          margin: const EdgeInsets.only(bottom: 10),
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                colorFilter: ColorFilter.mode(
                                    Colors.black.withOpacity(0.1), BlendMode.screen),
                                image:  NetworkImage('${postDetails.thumbnail}'),
                                fit: BoxFit.cover,
                              )),
                          child: _isLoading ? const Center(child: CircularProgressIndicator(),): Container(
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                  begin: Alignment.bottomCenter,
                                  end: Alignment.topCenter,
                                  colors: [
                                    const Color(0xff000000).withOpacity(1),
                                    const Color(0xff464646).withOpacity(0.3),
                                  ]),
                            ),
                            padding: const EdgeInsets.symmetric(horizontal: 20),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                Text(
                                  '${postDetails.title}',
                                  style: GoogleFonts.robotoSerif(
                                      color: const Color(0xfff2f2f2),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 24),
                                ),
                                const SizedBox(
                                  height: 60,
                                ),
                                Wrap(
                                  children: [
                                    for (int i=0; i < postDetails.categoriesName!.length; i++)
                                      GestureDetector(
                                        onTap: (){
                                          Navigator.push(context, MaterialPageRoute(builder: (context)=>CategoryWaysPostListScreen(title: '${postDetails.categoriesName?[i]}', id: '${postDetails.categoriesId?[i]}',)));
                                        },
                                        child: Container(
                                          decoration: const BoxDecoration(
                                              border: Border(left: BorderSide(width: 3,color: primaryColors))
                                          ),
                                          padding: const EdgeInsets.only(right: 10),
                                          child: Text(
                                            '  ${postDetails.categoriesName?[i]}',
                                            overflow: TextOverflow.clip,
                                            maxLines: 1,
                                            style: GoogleFonts.robotoSerif(
                                                color: const Color(0xfff2f2f2), fontSize: 16),
                                          ),
                                        ),
                                      ),
                                  ],
                                ),
                                const SizedBox(
                                  height: 16,
                                ),
                                Text(
                                  '${postDetails.shortContent}',
                                  overflow: TextOverflow.clip,
                                  maxLines: 5,
                                  style: const TextStyle(
                                      color: Color(0xffbababa), fontSize: 14),
                                ),
                                const SizedBox(
                                  height: 16,
                                ),
                              ],
                            ),
                          )),
                    ),
                    Positioned(
                      left: 10,
                      top: 42,
                      child: GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                        },
                        child: Container(
                            width: 50,
                            height: 50,
                            decoration: BoxDecoration(
                                color: Colors.black87.withOpacity(0.5),
                                borderRadius: BorderRadius.circular(30)),
                            child: const Icon(
                              Icons.arrow_back,
                              size: 30,
                              color: Colors.white,
                            )),
                      ),
                    ),

                  ],
                ),
              ),
              customSizeBox(10),
              Container(
                padding: const EdgeInsets.all(defaultAllSidePadding),
                child: Column(
                  children: [
                    Row(
                      crossAxisAlignment:CrossAxisAlignment.center,
                      mainAxisAlignment:
                      MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            Icon(
                              Icons.remove_red_eye_outlined,
                              color: Theme.of(context).iconTheme.color,
                              size: 22,
                            ),
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 10),
                              child: Text(
                                '${postDetails.views} ${getTranslated(context, 'views') ?? 'views'}',
                                style: GoogleFonts.robotoSerif(
                                  fontWeight: FontWeight.w300,
                                  fontSize: 16
                                ),
                              ),
                            ),
                          ],
                        ),
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10),
                          child: GestureDetector(
                            onTap: (){
                              bookMark();
                            },
                            child: Card(
                              elevation: elevation,
                              color: isBookMark ? primaryColors : Colors.white,
                              child: Padding(
                                padding: const EdgeInsets.all(3.0),
                                child: Icon(
                                  Icons.bookmark_border,
                                  size: 24,
                                  color: isBookMark ? Colors.white : primaryColors,
                                ),
                              ),
                            ),
                          ),),
      
                      ],
                    ),
                    customSizeBox(4),
                    Row(
                      crossAxisAlignment:CrossAxisAlignment.center,
                      mainAxisAlignment:
                      MainAxisAlignment.spaceBetween,
                      children: [
                        GestureDetector(
                          onTap: (){
                            Navigator.push(context, MaterialPageRoute(builder: (context)=>AuthorPostScreens(name: '${postDetails.authorName}', id: '${postDetails.authorId}', image: '${postDetails.authorAvatar}',randomNumber: postDetails.randomNumber ?? 0,)));
                          },
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            children: [
                              Hero(
                                tag: 'avatar-${postDetails.randomNumber}',
                                child: Container(
                                  width: 20,
                                  height: 20,
                                  clipBehavior:
                                  Clip.antiAlias,
                                  decoration: const BoxDecoration(
                                    shape: BoxShape.circle,
                                  ),
                                  child: Image.network(
                                    '${postDetails.authorAvatar}',
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 10),
                                child: Text(
                                  '${postDetails.authorName}',
                                  style: GoogleFonts.robotoSerif(
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
      
                        Row(
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            Icon(
                              Icons.calendar_month,
                              color: Theme.of(context).iconTheme.color,
                              size: 22,
                            ),
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 10),
                              child: Text(
                                '${postDetails.approvedAt}',
                                style: GoogleFonts.robotoSerif(
                                    fontWeight: FontWeight.w300,
                                    fontSize: 16
                                ),
                              ),
                            ),
                          ],
                        ),
      
                      ],
                    ),
                    customSizeBox(8),
                    Row(
                      crossAxisAlignment:CrossAxisAlignment.center,
                      mainAxisAlignment:
                      MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            Icon(
                              Icons.comment_bank_outlined,
                              color: Theme.of(context).iconTheme.color,
                              size: 22,
                            ),
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 10),
                              child: Text(
                                '${postDetails.comments} ${getTranslated(context, 'comments') ?? 'comments'}',
                                style: GoogleFonts.robotoSerif(
                                    fontWeight: FontWeight.w300,
                                    fontSize: 16
                                ),
                              ),
                            ),
                          ],
                        ),
                        GestureDetector(
                          onTap: (){
                            if(isAuth){
                              Navigator.push(context, MaterialPageRoute(builder: (context)=>CommentsScreen(postId: postDetails.postId!,)));
                            }else{
                              dialogLogin(context);
                            }

                          },
                          child: Card(
                            elevation: elevation,
                            color: Theme.of(context).primaryColor,
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  const Icon(
                                    Icons.messenger_outline_outlined,
                                    color: Colors.white,
                                    size: 22,
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.symmetric(horizontal: 10),
                                    child: Text(
                                      getTranslated(context, 'Comments') ?? 'Comments',
                                      style: GoogleFonts.robotoSerif(
                                          fontWeight: FontWeight.w300,
                                          fontSize: 16,
                                        color: Colors.white
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
      
                      ],
                    ),
                    customSizeBox(8),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                    children: List.generate(postDetails.details!.length,(index){
                      return PostDetailsWidget(postDetails: postDetails.details![index],);
                    })
                ),
              ),
              customSizeBox(20),
              sectionTitle((){
              },getTranslated(context, 'Tags') ?? 'Tags',false,context),
              Padding(padding: const EdgeInsets.all(defaultAllSidePadding),
              child: Wrap(
                children: [
                  for (int i=0; i < postDetails.tags!.length; i++)
                    Container(
                      decoration: const BoxDecoration(
                          border: Border(left: BorderSide(width: 3,color: primaryColors))
                      ),
                      padding: const EdgeInsets.only(right: 10),
                      child: Text(
                        '  ${postDetails.tags?[i]}',
                        overflow: TextOverflow.clip,
                        maxLines: 1,
                        style: GoogleFonts.robotoSerif( fontSize: 16),
                      ),
                    ),
                ],
              ),
              ),
      
              customSizeBox(20),
              sectionTitle((){

              },getTranslated(context, 'You Might also like') ?? 'You Might also like',false,context),
              customSizeBox(8),
              PostWidget(posts: relatedPost),
              customSizeBox(20),
      
            ],
          ),
        ),
      ),
    );
  }
}
