import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'package:mobile_portal_23/models/reportListModel.dart';
import 'package:mobile_portal_23/classes/common_classes.dart';
import 'dart:convert';
import 'package:mobile_portal_23/widgets/reportCardWidget.dart';

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

  @override
  State<dailyReportList> createState() => _dailyReportListState();
}

late EmployeePageArguments employeePageArguments;
//late EmployeeArguments empArgs;
bool _isError = false;
bool _isData = false;
//String? userApiKey; // = "XST8X8F-6Q9M1FG-PE9948X-SPFHVX9";
List<String> favoriteWorks = [];
List<ModelReportList> reportList = [];
bool _showFaworites = false;
Future<void> _saveFavoriteWorks(List<String> favoriteWorks) async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setStringList('favoriteWorks', favoriteWorks);
}

Future<void> getSharedPrefs() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  // userApiKey = prefs.getString("apiKey");
  favoriteWorks = prefs.getStringList("favoriteWorks") ?? [];
}

class _dailyReportListState extends State<dailyReportList> {
  String appDomain = "iotechnic.eu";

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final args = ModalRoute.of(context)!.settings.arguments as Map;

      employeePageArguments = args['userArgs'];
      //    empArgs = (ModalRoute.of(context)?.settings.arguments ??
      //    <String, dynamic>{}) as EmployeeArguments;
      //  getSharedPrefs().then((value) {
      fetchdata().then((data) {
        if (data != null) {
          for (var item in data) {
            reportList.add(ModelReportList.fromJson(item));
          }

          setState(() {
            _isData = true;
            debugPrint('Fetch ok.');
          });
        } else {
          _isError = true;
        }
        //employeeList = data;
      });
    });
    //  });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  Future fetchdata() async {
    var res = await http.get(

      // "http://iotechnic.eu/apiGetAllReport/X8B0PQS-2KYMCV3-G5WD74N-8G0CRAH");
        Uri.parse("http://$appDomain/apiGetAllReport/${employeePageArguments.apiKey!}"));
    //"http://192.168.0.144/apiGetDailyReport/X8B0PQS-2KYMCV3-G5WD74N-8G0CRAH");
    if (res.statusCode == 200) {
      var obj = json.decode(res.body);
      return obj;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Minden jelentés"),
          actions: [
            IconButton(
              icon: const Icon(Icons.search),
              onPressed: !_showFaworites
                  ? () {
                showSearch(
                  context: context,
                  delegate: ReportSearchDelegate(),
                );
                setState(() {});
              }
                  : null,
            ),
            IconButton(
                onPressed: () {
                  getSharedPrefs();
                  _showFaworites = !_showFaworites;
                  setState(() {});
                },
                icon: _showFaworites
                    ? const Icon(Icons.star, color: Colors.yellow)
                    : const Icon(Icons.star_border)),
            /* IconButton(
              icon: Icon(
                Icons.more_vert,
              ),
              onPressed: () {},
            )*/
          ],
          actionsIconTheme: const IconThemeData(
            size: 32,
          ),
        ),
        //drawer: Drawer(),
        body: page(context));
  }
}

class ReportSearchDelegate extends SearchDelegate {
  @override
  Widget? buildLeading(BuildContext context) => IconButton(
      onPressed: () => close(context, null),
      icon: const Icon(Icons.arrow_back));

  @override
  List<Widget>? buildActions(BuildContext context) {
    // TODO: implement buildActions
    IconButton(
        onPressed: () {
          if (query.isEmpty) {
            close(context, null);
          } else {
            query = "";
          }
        },
        icon: const Icon(Icons.clear));
    return null;
  }

  @override
  Widget buildResults(BuildContext context) {
    return Container(
      color: const Color(0xffECF0F1),
      child: ListView.builder(
        itemCount: reportList.length, // The length Of the array

        padding: const EdgeInsets.all(5),
        shrinkWrap: true,

        itemBuilder: (context, index) =>
            Container(child: reportCardWidget(reportList[index])
              //reportCard(context, reportList[index]),
            ),
      ),
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    // TODO: implement buildSuggestions
    List<ModelReportList> suggestions = reportList.where((element) {
      final result = element.title!.toLowerCase();
      final input = query.toLowerCase();
      return result.contains(input);
    }).toList();
    return Container(
      color: const Color(0xffECF0F1),
      child: ListView.builder(
        itemCount: suggestions.length, // The length Of the array

        padding: const EdgeInsets.all(5),
        shrinkWrap: true,

        itemBuilder: (context, index) =>
            Container(child: reportCardWidget(suggestions[index])
              //reportCard(context, suggestions[index]),
            ),
      ),
    );
  }
}

Container page(BuildContext context) {
  return _isData == false
      ? _isError
      ? Container(
    child: const AlertDialog(
        title: Text('Hálózati Hiba!'),
        content: Icon(Icons.error_outline),
        elevation: 24,
        backgroundColor: Colors.red),
  )
      : Container(
      child: SizedBox(
        height: MediaQuery.of(context).size.height / 1.3,
        width: MediaQuery.of(context).size.width,
        child: const Center(
          child: CircularProgressIndicator(),
        ),
      ))
      : gridList(context);
}

Container gridList(BuildContext context) {
  List<ModelReportList> reportList2 = [];
  if (_showFaworites) {
    reportList2 = reportList
        .where((element) => favoriteWorks.contains(element.sId))
        .toList();
  } else {
    reportList2 = reportList;
  }
  return Container(
    color: const Color(0xffECF0F1),
    child: ListView.builder(
      itemCount: reportList2.length, // The length Of the array

      padding: const EdgeInsets.all(5),
      shrinkWrap: true,

      itemBuilder: (context, index) => Container(
          child: reportCardWidget(
              reportList2[index]) //reportCard(context, _reportList[index]),
      ),
    ),
  );
}
/*
Card reportCard(BuildContext context, ModelReportList item) {
  int workHour = 0;
  bool workOpened = false;
  bool isFaworite = favoriteWorks.contains(item.sId);
  if (item.state!.contains("Opened")) workOpened = true;
  item.dailyReport.forEach((element) {
    workHour += element.employeeList.length;
  });
  return Card(
    clipBehavior: Clip.antiAlias,
    child: Column(
      children: [
        Badge(
          showBadge: !workOpened,
          position: BadgePosition.topEnd(top: 3, end: 3),
          badgeContent: Icon(Icons.lock_outlined),
          child: ListTile(
            tileColor: workOpened ? Colors.blue : Colors.grey,
            trailing: IconButton(
                onPressed: () {
                  if (isFaworite) {
                    favoriteWorks.remove(item.sId);
                  } else {
                    String? id = item.sId;
                    favoriteWorks.add(id!);
                  }
                  _saveFavoriteWorks(favoriteWorks);
                },
                icon: isFaworite
                    ? Icon(
                        Icons.star,
                        color: favoriteWorks.contains(item.sId)
                            ? Colors.yellow
                            : null,
                      )
                    : Icon(Icons.star_border)),
            /* Icon(
              Icons.keyboard_arrow_right,
              // size: 48,
              color: Colors.white,

            ),*/
            onTap: () {
              ReportArguments reportArgs = new ReportArguments(
                item.dailyReport,
                //userApiKey!,
                item.title!,
                item.sId!,
                item.state == "Opened" ? true : false,
                //employeePageArguments.isForeman!
              );
              Navigator.pushNamed(context, reportDetails.routeName, arguments: {
                'userArgs': employeePageArguments,
                'dataArgs': reportArgs
              });
            },
            leading: CircleAvatar(
                backgroundColor: Colors.white,
                child: Text(
                  item.dailyReport.length.toString(),
                  style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue),
                )),
            title: Text(
              item.title!,
              style: TextStyle(color: Colors.white),
            ),
            subtitle: Text(
              item.body!,
              style: TextStyle(color: Colors.black.withOpacity(0.6)),
            ),
          ),
        ),
        Padding(
            padding: const EdgeInsets.all(10.0),
            child: IntrinsicHeight(
                child: Column(children: [
              Row(children: [
                Text(
                  'KL' + item.workNumber!,
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.black.withOpacity(0.6)),
                ),
                VerticalDivider(color: Colors.grey, thickness: 1, width: 30),
                Text(
                  'Órák: ' + (workHour * 8).toString() + ' h',
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.black.withOpacity(0.6)),
                ),
                VerticalDivider(color: Colors.grey, thickness: 1, width: 30),
                Text(
                  'PO:' + item.poNumber!,
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.black.withOpacity(0.6)),
                ),
              ]),
              Divider(
                thickness: 1.0,
              ),
              Row(
                children: [
                  Flexible(
                    child: Text(
                      item.dailyReport[0].workTitle!,
                      style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: Colors.black.withOpacity(0.6)),
                    ),
                  )
                ],
              ),
              Divider(
                thickness: 1.0,
              ),
            ]))),
        /* ButtonBar(
          alignment: MainAxisAlignment.start,
          children: [
            ElevatedButton.icon(
                onPressed: () {
                  // Perform some action
                  ReportArguments arg = new ReportArguments(
                      reportList[index].dailyReport, userApiKey!);
                  Navigator.pushNamed(context, reportDetails.routeName,
                      arguments: arg);
                },
                icon: const Icon(Icons.mode_edit),
                label: const Text('Megnyitás')),
          ],
        ),*/
        //Image.asset('assets/card-sample-image-2.jpg'),
      ],
    ),
  );
}*/
