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

class reportCreate extends StatefulWidget {
  static const routeName = '/reportCreate';
  const reportCreate({Key? key}) : super(key: key);

  @override
  State<reportCreate> createState() => _reportCreateState();
}

late EmployeePageArguments employeePageArguments;

class _reportCreateState extends State<reportCreate> {
  String appDomain = "iotechnic.eu";
//  String? userApiKey; // = "XST8X8F-6Q9M1FG-PE9948X-SPFHVX9";
  //late List<ModelReportList> reportList = [];

  late List<WorkListModel> workList = [];
  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") ?? [];
  }

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

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

  late List<String> favoriteWorks = [];
  final bool _showFaworites = false;
  // late EmployeeArguments empArgs;
  bool _isError = false;
  bool _isData = false;
  @override
  void initState() {
    // TODO: implement initState
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final args = ModalRoute.of(context)!.settings.arguments as Map;

      employeePageArguments = args['userArgs'];
    });
    getSharedPrefs().then((value) {
      fetchdata().then((data) {
        if (data != null) {
          for (var item in data) {
            // reportList.add(ModelReportList.fromJson(item));
            workList.add(WorkListModel.fromJson(item));
          }
          _isData = true;
          setState(() {
            debugPrint('Fetch ok.');
          });
        } else {
          _isError = true;
        }
        //employeeList = data;
        /* empArgs = (ModalRoute.of(context)?.settings.arguments ??
            <String, dynamic>{}) as EmployeeArguments;*/
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Új jelentés')), body: page(context));
  }

  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> _reportList = [];
    List<WorkListModel> workList2 = [];
    if (_showFaworites) {
      workList2 = workList
          .where((element) => favoriteWorks.contains(element.sId))
          .toList();
    } else {
      workList2 = workList;
    }
    return Container(
      color: const Color(0xffECF0F1),
      child: ListView.builder(
        itemCount: workList2.length, // The length Of the array

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

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

  Card reportCard(BuildContext context, WorkListModel 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: [
          ListTile(
            tileColor: workOpened ? Colors.indigo : 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,
                )
                    : const Icon(Icons.star_border)),
            onTap: workOpened
                ? () {
              ReportArguments reportArgs = ReportArguments(
                List.empty(),
                //userApiKey!,
                item.title!,
                item.sId!,
                item.state == "Opened" ? true : false,
                //empArgs.isForeman!
              );

              Navigator.pushNamed(context, reportNew.routeName,
                  arguments: {
                    'userArgs': employeePageArguments,
                    'dataArgs': reportArgs
                  });
            }
                : null,
            title: Text(
              item.title!,
              style: const TextStyle(color: Colors.white),
            ),
            /*subtitle: Text(
              item.body!,
              style: TextStyle(color: Colors.yellow.withOpacity(0.6)),
            ),*/
          ),
          Padding(
              padding: const EdgeInsets.all(10.0),
              child: IntrinsicHeight(
                  child: Column(children: [
                    Text(
                      item.body!.replaceAll("\n", " "),
                      style: TextStyle(color: Colors.green.withOpacity(0.6)),
                    ),
                    const Divider(
                      thickness: 1.0,
                    ),
                    Row(children: [

                      Text(
                        'KL${item.workNumber!}',
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.black.withOpacity(0.6)),
                      ),
                      const VerticalDivider(color: Colors.grey, thickness: 1, width: 30),
                      Text(
                        'PO: ${item.poNumber!}',
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.black.withOpacity(0.6)),
                      ),
                    ]),
                  ]))),
        ],
      ),
    );
  }
}
