
import 'package:flutter/material.dart';
import 'package:top_news_app/helper/custom_appbar.dart';
import 'package:top_news_app/localization/localization.dart';
import 'package:top_news_app/model/Article.dart';
import 'package:top_news_app/widget/bookmark_news_card_one.dart';
import '../providers/article_provider.dart';
import '../services/storage_service.dart';


class BookMarkScreen extends StatefulWidget {
  const BookMarkScreen({Key? key}) : super(key: key);

  @override
  State<BookMarkScreen> createState() => _BookMarkScreenState();
}

class _BookMarkScreenState extends State<BookMarkScreen> {

  bool isAuth = false;
  var storage = StorageService();
  var articleProvider = ArticleProvider();
  List<ArticleData> posts = [];
  bool _isLoading = false;

  checkAuth() async {
    isAuth = (await storage.isAuthInLocal())!;
    await readJson();
  }


  Future<void> readJson() async {
    if(!isAuth){
      Navigator.pushReplacementNamed(context, '/email-login');
    }else{
      posts = (await articleProvider.bookmarkPosts())!;
    }
    setState(() {
      _isLoading = true;
    });
  }

  removeFormTheBookMark(ArticleData data) async{
    await articleProvider.bookMarking(data.postId);
  }

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

  @override
  Widget build(BuildContext context) {
    return SafeArea(child: RefreshIndicator(
      onRefresh: () async {
        return await checkAuth();
      },
      child: Scaffold(
        appBar: customAppBar(
            '${getTranslated(context, 'Bookmark') ?? 'Bookmark'} ',
            'back', context),
        body: _isLoading
            ? ListView.builder(
          itemCount: posts.length,
          itemBuilder: (BuildContext context, int index) {
            return Dismissible(
              key: UniqueKey(),
              background: Container(
                color: Colors.red,
                padding: const EdgeInsets.all(10),
                child: const Align(
                    alignment: Alignment.centerRight,
                    child: Icon(Icons.delete)),
              ),
              onDismissed: (directions) {
                removeFormTheBookMark(posts[index]);
              },
              child: BookMarkNewsCardOne(post: posts[index]),
            );
          },
        )
            : const Center(
          child: CircularProgressIndicator(),
        )
      ),
    ));
  }
}
