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

class reportDetails extends StatefulWidget {
  const reportDetails({Key? key}) : super(key: key);
  static const routeName = '/reportDetails';
  @override
  State<reportDetails> createState() => _reportDetailsState();
}

late EmployeePageArguments employeePageArguments;
late ReportArguments reportArguments;
//late String userApiKey = ""; //"X8B0PQS-2KYMCV3-G5WD74N-8G0CRAH";
bool _isData = false;
List<ModelEmployee> employeeList = [];

class _reportDetailsState extends State<reportDetails> {
  String appDomain = "iotechnic.eu";

  Future fetchEmployeeList() async {
    var res = await http.get(Uri.parse("http://$appDomain/apiemployeelist/${employeePageArguments.apiKey!}"));

    if (res.statusCode == 200) {
      var obj = json.decode(res.body);
      return obj;
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initializeDateFormatting();
    Intl.defaultLocale = "HU"; //sets global,

    WidgetsBinding.instance.addPostFrameCallback((_) {
      /*final arguments = (ModalRoute.of(context)?.settings.arguments ??
          <String, dynamic>{}) as ReportArguments;*/
      //var args = ModalRoute.of(context)!.settings.arguments;
      //userApiKey = arguments.userApiKey; // as List<DailyReport>;
      final args = ModalRoute.of(context)!.settings.arguments as Map;

      employeePageArguments = args['userArgs'];
      reportArguments = args['dataArgs'];

      fetchEmployeeList().then((data) {
        if (data != null) {
          for (var item in data) {
            employeeList.add(ModelEmployee.fromJson(item));
          }
          _isData = true;
          setState(() {
            debugPrint('Fetch ok.');
          });
        }
        //employeeList = data;
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    /* final arguments = (ModalRoute.of(context)?.settings.arguments ??
        <String, dynamic>{}) as ReportArguments;*/
    final args = ModalRoute.of(context)!.settings.arguments as Map;

    employeePageArguments = args['userArgs'];
    reportArguments = args['dataArgs'];
    return Scaffold(
        appBar: AppBar(
          title: const Text("Minden jelentés"),
          /*   actions: [
            IconButton(
              icon: Icon(Icons.search),
              onPressed: () {},
            ),
            IconButton(
              icon: Icon(
                Icons.more_vert,
              ),
              onPressed: () {},
            )
          ],*/
          actionsIconTheme: const IconThemeData(
            size: 32,
          ),
        ),
        bottomNavigationBar: reportArguments.state //arguments.state
            ? null
            : const BottomAppBar(
            child: SizedBox(
                height: 30,
                child: Icon(
                  Icons.lock,
                  color: Colors.red,
                ))),
        //drawer: Drawer(),
        body: _isData
            ? gridList(context)
            : Container(
            child: SizedBox(
              height: MediaQuery.of(context).size.height / 1.3,
              width: MediaQuery.of(context).size.width,
              child: const Center(
                child: CircularProgressIndicator(),
              ),
            )),
        floatingActionButton: Visibility(
          visible: reportArguments.state && employeePageArguments.isForeman!,
          child: FloatingActionButton(
            onPressed: () => {
              Navigator.pushNamed(context, reportNew.routeName, arguments: {
                'userArgs': employeePageArguments,
                'dataArgs': reportArguments
              }).then((value) {
                setState(() {});
              }),
            },
            child: const Icon(Icons.add),
          ),
        ));
    //    );
  }
}

Container gridList(BuildContext context) {
  /*final arguments = (ModalRoute.of(context)?.settings.arguments ??
      <String, dynamic>{}) as ReportArguments;*/
  //var args = ModalRoute.of(context)!.settings.arguments;
  List<DailyReport> reportDetailsList =
      reportArguments.report; //arguments.report; // as List<DailyReport>;
  return Container(
    color: const Color(0xffECF0F1),
    child: ListView.builder(
      itemCount: reportDetailsList.length, // The length Of the array

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

      /* gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisSpacing: 1,
        mainAxisSpacing: 1,
        crossAxisCount: 1,
        childAspectRatio: (4 / 3),
      ),
      */
      itemBuilder: (context, index) => Container(
        child: reportDetailsCard(context, index),
      ),
    ),
  );
}

Card reportDetailsCard(BuildContext context, int index) {
  bool workOpened = false;
  ModelEmployee findEmployee(String id) =>
      employeeList.firstWhere((emlement2) => emlement2.sId == id);
  //String languageCode = Localizations.localeOf(context).languageCode;
  /* final arguments = (ModalRoute.of(context)?.settings.arguments ??
      <String, dynamic>{}) as ReportArguments;*/
  //var args = ModalRoute.of(context)!.settings.arguments;
  List<DailyReport> reportDetailsList =
      reportArguments.report; //arguments.report;

  String? foreManName = findEmployee(reportDetailsList[index].foremanId!)
      .name; //employeeList.where((element) => element.sId == reportDetailsList[index].foremanId!);

  return Card(
    clipBehavior: Clip.antiAlias,
    child: Column(
      children: [
        ListTile(
          tileColor: reportArguments.state ? Colors.cyan : Colors.grey,
          trailing: employeePageArguments.isForeman!
              ? Icon(
            Icons.edit,

            // size: 48,
            color: reportArguments.state ? Colors.white : Colors.grey,
          )
              : null,
          onTap: reportArguments.state && employeePageArguments.isForeman!
              ? () {
            /* ReportArguments arg = new ReportArguments(
                  reportList[index].dailyReport, userApiKey!);
              Navigator.pushNamed(context, reportDetails.routeName,
                  arguments: arg);*/
          }
              : null,
          leading: CircleAvatar(
              backgroundColor: Colors.white,
              child: Text(
                //reportDetailsList[index].employeeList.length.toString(),
                DateFormat('EE').format(DateFormat('yyyy.MM.dd')
                    .parse(reportDetailsList[index].date!)),
                style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.blue),
              )),
          title: Text(
            foreManName!,
            // reportDetailsList[index].foremanId!,

            style: const TextStyle(color: Colors.white, fontSize: 18),
          ),
          subtitle: Text(
            reportDetailsList[index].date!,
            style: TextStyle(color: Colors.black.withOpacity(0.6)),
          ),
        ),

        Padding(
            padding: const EdgeInsets.all(10.0),
            child: IntrinsicHeight(
                child: Column(children: [
                  Row(children: [
                    Flexible(
                      child: Text(
                        reportDetailsList[index].workTitle!,
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.black.withOpacity(0.6)),
                      ),
                    ),
                  ]),
                  const Divider(
                    thickness: 1.0,
                  ),
                  Column(
                    children: reportDetailsList[index]
                        .employeeList
                        .map(
                          (e) => Text(
                        '• ${findEmployee(e).name!}',
                        style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.black.withOpacity(0.6)),
                      ),
                    )
                        .toList(),
                  ),
                  const Divider(
                    thickness: 1.0,
                  ),
                ]))),
        /*  ButtonBar(
          alignment: MainAxisAlignment.start,
          children: [
            ElevatedButton.icon(
                onPressed: () {
                  // Perform some action

                  /*  Navigator.pushNamed(context, reportDetails.routeName,
                      arguments: reportList[index]);*/
                },
                icon: const Icon(Icons.mode_edit),
                label: const Text('Szerkeszt')),
          ],
        ),*/
        //Image.asset('assets/card-sample-image-2.jpg'),
      ],
    ),
  );
}
