import 'package:flutter/material.dart';
import 'package:mobile_portal_23/classes/common_classes.dart';
import 'package:mobile_portal_23/models/employee_model.dart';
import 'package:mobile_portal_23/models/reportListModel.dart';
import 'package:intl/intl.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
//import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

//String? userApiKey;
TextEditingController dateinput = TextEditingController();
String appDomain = "iotechnic.eu";
bool _enableSave = false;
bool _textMessageOK = false;
String textMessage = "";
late EmployeePageArguments employeePageArguments;
late ReportArguments reportArguments;
/*Future<Null> getSharedPrefs() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  userApiKey = prefs.getString("apiKey");
}*/

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

Future fetchReport(BuildContext context) async {
  var res = await http.get(Uri.parse("http://$appDomain/apiGetAllReport/${employeePageArguments.apiKey!}"));
  if (res.statusCode == 200) {
    var data = json.decode(res.body);
    //return obj;
    if (data != null) {
      for (var item in data) {
        ModelReportList mr = ModelReportList.fromJson(item);

        if (mr.sId == reportArguments.workId) {
          reportArguments.report.clear();
          reportArguments.report.addAll(mr.dailyReport);
        }
      }

      //employeeList = data;
    }
  }
}

Future fetchEmployeeData(String userApiKey) async {
  var res = await http.get(

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

Future<List<EmployeeLs>> fetchData(String userApiKey) async {
  var url = "http://$appDomain/apiemployeelist/$userApiKey";
  http.Response response = await http.get(Uri.parse(url));
  var resp = jsonDecode(response.body);
  print(resp.toString());

  return resp.map<EmployeeLs>((m) => EmployeeLs.fromJson(m)).toList();
}

Future<String> postDailyReport(var json) async {
  final response = await http.post(
    Uri.parse("http://$appDomain/apiPostDailyReport/${employeePageArguments.apiKey!}"),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(json),
  );

  if (response.statusCode == 200) {
    // If the server did return a 201 CREATED response,
    // then parse the JSON.
    return response.body;
  } else {
    // If the server did not return a 201 CREATED response,
    // then throw an exception.
    throw Exception('Failed to create album.');
  }
}

_saveForm(BuildContext context, ReportArguments arguments,
    List<EmployeeLs> employeeList) {
  EasyLoading.show(status: 'Mentés...');
  // _onLoading2();
  print("SUBMITTED!");
  print(dateinput.text);
  print("Title: ${arguments.workName}");
  print("WorkId: ${arguments.workId}");
  print("Message: $textMessage");
  List<String> emp = [];
  //print("Jelenlévők: ");
  for (var hobby in employeeList) {
    if (hobby.value == true) {
      //print(hobby.name);
      emp.add(hobby.id);
    }
  }
  var report = {
    'userApiKey': employeePageArguments.apiKey,
    'workId': arguments.workId,
    'date': dateinput.text,
    'msg': textMessage,
    'employeeList': emp
  };
  //print(json.encode(report));
  postDailyReport(report).then((value) {
    if (value.contains("OK")) {
      EasyLoading.showSuccess('Sikeres Mentés');
      fetchReport(context).then((value) {
        Future.delayed(const Duration(seconds: 3), () {
          // Navigator.pop(context); //pop dialog
          EasyLoading.dismiss();

          Navigator.of(context).pop();
          //_login();
        });
      });
    }
  });
}

class _reportNewState extends State<reportNew> {
  final _formKey = GlobalKey<FormState>();
  List<EmployeeLs> employeeList = [];
  bool _isData = false;
  @override
  void initState() {
    // TODO: implement initState
    // getSharedPrefs().then((args) {
    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'];
      fetchData(employeePageArguments.apiKey!).then((value) {
        setState(() {
          employeeList.addAll(value);
          _isData = true;
        });
      });
    });
    // });
    dateinput.text = DateFormat('yyyy.MM.dd').format(DateTime.now());
    //set output date to TextField value
    super.initState();
  }

  checkize() {
    _enableSave = false;
    for (var item in employeeList) {
      if (item.value == true) {
        setState(() {
          if (_textMessageOK) _enableSave = true;
        });

        print("Save Enabled");
      }
    }
  }

  Widget _buildLastName() {
    return Form(
        key: _formKey,
        //margin: const EdgeInsets.only(left: 40),
        child: TextFormField(
            validator: (value) {
              if (value == null || value.isEmpty) {
                textMessage = "";
                _textMessageOK = false;
                checkize();
                return 'A mező nem lehet üres!';
              }
              if (value.length < 3) {
                textMessage = "";
                _textMessageOK = false;
                checkize();
                return "Legalább 3 karakter!";
              } else {
                textMessage = value;
                _textMessageOK = true;
                checkize();
                return null;
              }
            },
            onChanged: (_) {
              _formKey.currentState!.validate();
            },
            onFieldSubmitted: (_) {
              _formKey.currentState!.validate();
            },
            style: const TextStyle(
                color: Color.fromARGB(255, 3, 163, 29),
                fontFamily: 'RadikalLight'),
            decoration: //_buildInputDecoration("Last name", ''),
            const InputDecoration(labelText: 'Munka leírása')));
  }

  Container gridList(BuildContext context) {
    //_enableSave = false;

    return Container(
      color: Colors.white,
      child: ListView.builder(
        itemCount: employeeList.length, // The length Of the array

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

        itemBuilder: (context, index) => Container(
          child: employeeWidget(context, index),
        ),
      ),
    );
  }

  SwitchListTile employeeWidget(BuildContext context, index) {
    return SwitchListTile(
      //controlAffinity: ListTileControlAffinity.trailing,
        activeColor: Colors.green,
        value: employeeList[index].value,
        title: Text(employeeList[index].name),
        onChanged: (newValue) {
          setState(() {
            employeeList[index].value = newValue;
            checkize();
          });
        });
  }

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

  @override
  Widget build(BuildContext context) {
    List<String> emp = [];
    /*  final arguments =
        ModalRoute.of(context)!.settings.arguments as ReportArguments;*/
    final args = ModalRoute.of(context)!.settings.arguments as Map;

    employeePageArguments = args['userArgs'];
    reportArguments = args['dataArgs'];
    //<String, dynamic>{}) as ReportArguments;
    return Scaffold(
      //resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title: const Text("Új jelentés"),
          actions: [
            IconButton(
              icon: const Icon(Icons.search),
              onPressed: () {},
            ),
            /* IconButton(
                icon: Icon(
                  Icons.save,
                  //color: Colors.white,
                ),
                onPressed: _enableSave
                    ? () {
                        print("Save");
                      }
                    : null)*/
          ],
          actionsIconTheme: const IconThemeData(
            size: 32,
          ),
        ),
        //drawer: Drawer(),

        body: SingleChildScrollView(
          child: page(context),
        ),
        bottomNavigationBar: BottomAppBar(
          color: Colors.cyan,
          child: Container(
            height: 50.0,
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Visibility(
          visible: _enableSave,
          child: FloatingActionButton(
            onPressed: _enableSave
                ? () => {
              if (_formKey.currentState!.validate())
                {
                  /* print("SUBMITTED!"),
                          print(dateinput.text),
                          print("Title: " + arguments.workName),
                          print("WorkId: " + arguments.workId),
                          print("Message: " + textMessage),

                          //print("Jelenlévők: ");
                          for (var hobby in employeeList)
                            {
                              if (hobby.value == true)
                                {
                                  //print(hobby.name);
                                  emp.add(hobby.id),
                                }
                            },
                          print(emp),*/
                  // TODO submit

                  _saveForm(context, reportArguments, employeeList)
                }
              // Navigator.pushNamed(context, reportNew.routeName,
              //   arguments: arguments),
            }
                : null,
            child: const Icon(Icons.save),
          ),
        ));
  }

  Widget page(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'];
    List<DailyReport> reportDetailsList =
        reportArguments.report; // as List<DailyReport>;
    String textMessage = "";

    DateTime selectedDate = DateTime.now();
    return Container(
      child: Column(children: [
        Card(
          clipBehavior: Clip.antiAlias,
          child: Column(
            children: [
              ListTile(
                tileColor: Colors.cyan,
                /*  trailing: IconButton(
                    color: Colors.green,
                 icon: Icon(
                      Icons.save,
                      //color: Colors.white,
                    ),
                    onPressed: _enableSave
                        ? () {
                            print("Save");
                          }
                        : null),*/
                /* ReportArguments arg = new ReportArguments(
                  reportList[index].dailyReport, userApiKey!);
              Navigator.pushNamed(context, reportDetails.routeName,
                  arguments: arg);*/

                title: Text(
                  reportArguments.workName,
                  // reportDetailsList[index].foremanId!,

                  style: const TextStyle(color: Colors.white, fontSize: 18),
                ),
                /*subtitle: Text(
                "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(
                          arguments.workName,
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.black.withOpacity(0.6)),
                        ),
                      ),
                    ]),
                    Divider(
                      thickness: 1.0,
                    ),*/
                        Container(
                          padding: const EdgeInsets.only(left: 10, right: 10),
                          child: Center(
                              child: TextField(
                                //enabled: datePickerEnabled,
                                controller:
                                dateinput, //editing controller of this TextField
                                decoration: const InputDecoration(
                                    icon:
                                    Icon(Icons.calendar_today), //icon of text field
                                    labelText: "Jelentés Dátuma" //label text of field
                                ),
                                readOnly:
                                true, //set it true, so that user will not able to edit text
                                onTap: () async {
                                  DateTime? pickedDate = await showDatePicker(
                                      context: context,
                                      initialDate: DateTime.now(),
                                      firstDate: DateTime(
                                          2020), //DateTime.now() - not to allow to choose before today.
                                      lastDate: DateTime.now());

                                  if (pickedDate != null) {
                                    //print(pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                                    String formattedDate =
                                    DateFormat('yyyy.MM.dd').format(pickedDate);
                                    //print(formattedDate); //formatted date output using intl package =>  2021-03-16
                                    //you can implement different kind of Date Format here according to your requirement

                                    //  setState(() {
                                    //textMessageEnabled = true;
                                    selectedDate = pickedDate;

                                    dateinput.text =
                                        formattedDate; //set output date to TextField value.
                                    //  });
                                  } else {
                                    print("Nem választott dátumot!");
                                  }
                                },
                              )),
                        ),
                        Container(
                          padding: const EdgeInsets.only(top: 20, left: 15, right: 15),
                          //margin: const EdgeInsets.only(left: 5, right: 5),
                          height: 100,
                          //child: Padding(
                          //padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),

                          child: _buildLastName(),
                        ),
                        const Divider(
                          thickness: 1.0,
                        ),
                        SizedBox(
                            height: 300,
                            child: _isData
                                ? gridList(context)
                                : SizedBox(
                              height:
                              MediaQuery.of(context).size.height / 1.3,
                              width: MediaQuery.of(context).size.width,
                              child: const Center(
                                child: CircularProgressIndicator(),
                              ),
                            ))
                        //ListView(children: UsersUi(arguments.userApiKey)),

                        /*new Column(
                    children: reportDetailsList[index]
                        .employeeList
                        .map(
                          (e) => new Text(
                            '• ' + findEmployee(e).name!,
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Colors.black.withOpacity(0.6)),
                          ),
                        )
                        .toList(),
                  ),
                 */
                      ]))),
            ],
          ),
        ),
      ]),
    );
  }
}
