
import 'package:flutter/material.dart';
import 'package:top_news_app/helper/custom_appbar.dart';
import 'package:top_news_app/helper/helper.dart';
import 'package:top_news_app/helper/image_cached.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:top_news_app/localization/localization.dart';
import 'package:top_news_app/model/Comment.dart';
import 'package:top_news_app/model/auth.dart';
import 'package:top_news_app/model/user.dart';
import 'package:top_news_app/providers/article_provider.dart';
import 'package:top_news_app/services/storage_service.dart';


class CommentsScreen extends StatefulWidget {
  final num postId;
  const CommentsScreen({super.key, required this.postId});

  @override
  State<CommentsScreen> createState() => _CommentsScreenState();
}

class _CommentsScreenState extends State<CommentsScreen> {

  var auth = Auth();
  User user= User();
  bool isAuth = false;
  var storage = StorageService();
  var message = TextEditingController();
  var articleProvider = ArticleProvider();
  List<CommentData> feedComments = [];
  int page = 0;
  final scrollController = ScrollController();


  late  bool _isLoading = true;
  bool isLoadingMore = true;
   loadingEffect() async {
    await getComments();
      setState(() {
        _isLoading = false;
      });

  }

  storeTheComment() async{
     try{
       var result = await articleProvider.commentStore(widget.postId,message.text);
       if(result.containsKey('message')){
         showMessage(result['message']);
         message.text = '';
       }

       //set in preferences
       if(result.containsKey('errors')){
         result['errors'].forEach((key, value){
           showMessage(value[0]);
         });
       }
     }catch(e){
       rethrow;
     }

  }

  getAuthData() async{
    isAuth = (await storage.isAuthInLocal())!;
    if(isAuth){
      auth = await storage.getAuthUserDataFromStorage();
    }
    setState(() {

    });
  }


  getComments() async{
     try{
       List<CommentData> data = (await articleProvider.getCommentData(widget.postId , page))!;
       //update products
       if (page == 0) {
         feedComments = data;
       } else {
         feedComments.addAll(data);
       }
          }catch(e){
       rethrow;
     }


    setState(() {

    });
  }



  @override
  void initState() {

    super.initState();
    scrollController.addListener(_scrollListener);
    page = 0;
    loadingEffect();
    getAuthData();
  }

  void _scrollListener() async {
    if (scrollController.position.pixels ==
        scrollController.position.maxScrollExtent) {

      setState(() {
        isLoadingMore   = true;
      });
      page = page + 1;
      await getComments();
      setState(() {
        isLoadingMore = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return SafeArea(child: RefreshIndicator(
      onRefresh: () async{
        return await loadingEffect();
      },
      child: Scaffold(
        appBar: customAppBar(getTranslated(context, 'Comments') ?? 'Comments', 'back', context),
        body: _isLoading ? const Center(child: CircularProgressIndicator(),) : Column(
          children: [
            Expanded(
              child: feedComments.isNotEmpty ?  ListView.builder(
                controller: scrollController,
                  itemCount: feedComments.length,
                  itemBuilder: (context,int index){
                    return Card(
                      elevation: elevation,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 2),
                        child: Column(
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                SizedBox(
                                  width: 90,
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Container(
                                        decoration: const BoxDecoration(
                                          shape: BoxShape.circle,
                                        ),
                                        child:  ImageCached(
                                            blur: false,
                                            height: 70, width: 70, image: feedComments[index].avatar,fit: BoxFit.cover),
                                      ),
                                      customSizeBox(10),
                                    ],
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(left: 10),
                                  child: SizedBox(
                                    width: size.width - 150,
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '${feedComments[index].name}',
                                          style:  GoogleFonts.roboto(
                                              fontWeight: FontWeight.w700, fontSize: 18),
                                        ),
                                        customSizeBox(8),
                                        Text(
                                          '${feedComments[index].message}',
                                          maxLines: 2,
                                          style:  GoogleFonts.roboto(
                                              fontWeight: FontWeight.w400, fontSize: 14),
                                        ),
                                        customSizeBox(5),

                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Align(
                              alignment: Alignment.bottomRight,
                              child: Container(
                                padding:  const EdgeInsets.all(4),
                                child: Text('${feedComments[index].date}',style: GoogleFonts.robotoSerif(fontWeight: FontWeight.w600,fontSize: 12),),
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  }) : Center(
                child: Text(getTranslated(context, 'No Comments') ?? 'No Comments'),
              ),
            ),

             Container(
          height: 100,
          padding: const EdgeInsets.all(10),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
               Expanded(
                child: TextField(
                  controller: message,
                  decoration:  InputDecoration(
                    labelText: "  ${getTranslated(context, 'Write Comments here') ?? 'Write Comments here'}",
                    contentPadding: const EdgeInsets.symmetric(vertical: 12.0,horizontal: 5),
                    focusedBorder: const OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.grey, width: 1),
                    ),
                    enabledBorder: const OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.grey, width: 1),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 8.0),
              IconButton(onPressed: (){
                storeTheComment();
              }, icon: const Icon(Icons.send_sharp,color: primaryColors,size: 36,)),
            ],
          ),
        ),
          ],
        ),
      ),
    ));
  }
}
