
import 'package:flutter/material.dart';
import 'package:top_news_app/localization/localization.dart';
import 'package:top_news_app/model/Article.dart';
import 'package:top_news_app/services/article_service.dart';
import 'package:top_news_app/widget/newscard_widget_sm_one.dart';

class CustomSearch extends SearchDelegate {
  var articleService = ArticleService();

  Future<List<ArticleData>> _search() async{
    Article article;
    var response = await articleService.getArticleSearch(query);
    Map parse = response;
    article = Article.fromJson(parse);
    return article.data!;
  }


  @override
  List<Widget> buildActions(BuildContext context) {

    return [
      IconButton(
          icon: const Icon(Icons.clear),
          onPressed: () {
            query = "";
          })
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {

    return IconButton(
        icon: const Icon(Icons.arrow_back),
        onPressed: () {
          close(context, null);
        });
  }

  @override
  Widget buildResults(BuildContext context) {

    throw UnimplementedError();
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return FutureBuilder<List<ArticleData>>(
      future: _search(),
      builder: (context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
            return const Center(
              child: CircularProgressIndicator(),
            );
          default:
            if (snapshot.hasError || !snapshot.hasData){
              return Center(
                child: Text(getTranslated(context, 'No Result Found') ?? 'No Result Found'),
              );
            } else {
              return ListView.builder(
                itemCount: snapshot.data?.length ?? 0,
                itemBuilder: (BuildContext context, int index) {
                  return NewsCardWidgetSmOne(post: snapshot.data![index]);
                },
              );
            }
        }
      },
    );

  }
}
