import 'package:flutter/material.dart';
import 'package:dropdown_search/dropdown_search.dart';
//import 'package:flutter/rendering.dart';
import 'package:intl/intl.dart';
import '../models/employee_model.dart';
//import '../http_service.dart';
//import '../post_model.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:expandable/expandable.dart';
//import 'package:shared_preferences/shared_preferences.dart';
import 'package:mobile_portal_23/classes/common_classes.dart';

late EmployeePageArguments employeePageArguments;
String appDomain = "iotechnic.eu";
//String appDomain = "192.168.0.144";
GlobalKey _key = GlobalKey();
List<Widget> appbarAct = [
  const IconButton(
    icon: Icon(Icons.save),
    tooltip: 'Open shopping cart',
    onPressed: null,
  )
];

class DailyReportApp extends StatelessWidget {
  final State<StatefulWidget>? homeBodyState = _key.currentState;

   DailyReportApp({super.key});

  @override
  Widget build(BuildContext context) {
    return DailyReport(key: key);
    /*Scaffold(
      appBar: AppBar(
          title: Text('Napi Jelentés'),
          elevation: 10.0,
          leading: Icon(Icons.arrow_back_ios_new),
          actions: appbarAct),
      body: DailyReport(key: _key),
      backgroundColor: Colors.grey[300],
    );*/
  }
}

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

  @override
  _DailyReportState createState() => _DailyReportState();
}

class EmpList {
  String? id;
  String? name;
  bool? value;
}

class _DailyReportState extends State<DailyReport> {
  //final HttpService httpService = HttpService();
  String dropdownValue = 'One';
  DateTime selectedDate = DateTime.now();
  bool datePickerEnabled = false;
  bool textMessageEnabled = false;
  bool isSwitched = false;
  TextEditingController dateinput = TextEditingController();
  List<Widget> switches = [];
  List<EmpList> emplist = [];
  //Future<List<EmployeeLs>> futureEmployee;
  List<EmployeeLs> employeeList = [];
  List<WorkLs> workList = [];
  bool _isData = false;
  String textMessage = "";
  // String selectedWork = "";
  bool saveEnabled = false;
  bool _textMessageOK = false;
  WorkLs? selectedWork; // "XST8X8F-6Q9M1FG-PE9948X-SFPHVX9"
  String? userApiKey; // = "XST8X8F-6Q9M1FG-PE9948X-SPFHVX9";
  final bool _expanded = false;
  final bool _appBarSaveEnabled = false;
  var currentFocus;
  /*Future<Null> getSharedPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userApiKey = prefs.getString("apiKey");
  }*/

  unfocus() {
    currentFocus = FocusScope.of(context);

    if (!currentFocus.hasPrimaryFocus) {
      currentFocus.unfocus();
    }
  }

  /*_loadApiKey() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString('apiKey');
  }*/

  Future fetchdata() async {
    print("http://$appDomain/apiGetDailyReport/${employeePageArguments.apiKey!}");
    var res = await http.get(

      // "http://iotechnic.eu/apiemployeelist/X8B0PQS-2KYMCV3-G5WD74N-8G0CRAH");

        Uri.parse("http://$appDomain/apiGetDailyReport/${employeePageArguments.apiKey!}")); //userApiKey!));

    //"http://192.168.0.144/apiGetDailyReport/X8B0PQS-2KYMCV3-G5WD74N-8G0CRAH");
    if (res.statusCode == 200) {
      var obj = json.decode(res.body);
      return obj;
    }
  }

  _print(String p) {
    print(p);
  }

  _enableSave() {
    setState(() {
      appbarAct = [
        IconButton(
            icon: const Icon(Icons.save),
            tooltip: 'Open shopping cart',
            onPressed: saveEnabled ? _print("Save Click") : null),
      ];
    });
  }

  _saveForm() {
    EasyLoading.show(status: 'Mentés...');
    // _onLoading2();
    debugPrint(DateFormat('yyyy-MM-dd').format(selectedDate));
    debugPrint("Title: ${selectedWork!.title}");
    debugPrint("WorkId: ${selectedWork!.id}");
    debugPrint("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': userApiKey,
      'workId': selectedWork?.id,
      'date': DateFormat('yyyy.MM.dd').format(selectedDate),
      'msg': textMessage,
      'employeeList': emp
    };
    //print(json.encode(report));
    postDailyReport(report).then((value) {
      if (value.contains("OK")) {
        EasyLoading.showSuccess('Sikeres Mentés');
        Future.delayed(const Duration(seconds: 3), () {
          // Navigator.pop(context); //pop dialog
          EasyLoading.dismiss();

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

  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.');
    }
  }

  @override
  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) {
    });
      print("KEY: ${employeePageArguments.apiKey}");
      fetchdata().then((data) {
        for (var item in data["employeeList"]) {
          //debugPrint(item["_id"]);
          employeeList.add(EmployeeLs(
              id: item["_id"], name: item["name"], value: false));
        }
        for (var item in data["workList"]) {
          debugPrint(item["_id"]);
          workList.add(WorkLs(
            id: item["_id"],
            title: item["title"],
            body: item["body"],
            state: item["state"] ??"",
            //value: false
          ));
        }
        _isData = true;
        setState(() {
          debugPrint('Fetch ok.');
        });
        //employeeList = data;
      });

    //userApiKey = _loadApiKey();
    _enableSave();
    //_isData = false;
    dateinput.text = ""; //set the initial value of text field
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is removed from the
    // widget tree.

    super.dispose();
  }

  Column myUi() {
    saveEnabled = false;
    _enableSave();
    //debugPrint("UI Update." + _isData.toString());
    return Column(
        children: employeeList.map((hobby) {
          if (hobby.value == true) {
            saveEnabled = true;
            _enableSave();
            // debugPrint(hobby.name);
          }

          return SwitchListTile(
            //controlAffinity: ListTileControlAffinity.trailing,
              activeColor: Colors.green,
              value: hobby.value,
              title: Text(hobby.name),
              onChanged: _textMessageOK == false
                  ? null
                  : (newValue) {
                setState(() {
                  hobby.value = newValue;
                });
              });
        }).toList());
  }

  DropdownSearch workUi() {
    return DropdownSearch<WorkLs>(

        //mode: Mode.MENU,
        //showSelectedItem: true,
        items: workList,
        /*.map((e) {
          return DropdownMenuItem<WorkLs>(child: Text(e.title), value: e);
        }).toList(),*/
        //showSearchBox: true,
        //;["Brazil", "Italia (Disabled)", "Tunisia", 'Canada'],
        //label: "Munka kiválasztása",
       // hint: "country in menu mode",
        //popupItemDisabled: (String s) => s.startsWith('I'),
        onChanged: (data) {
          //_dateSelected();
          selectedWork = data;

          //_selectDate(context);
          setState(() {
            datePickerEnabled = true;
          });
        });
  }

  @override
  Widget build(BuildContext context) => GestureDetector(
      onTap: () {
        //_enableSave();
        FocusScope.of(context).unfocus();
      },
      child: Scaffold(
          appBar: AppBar(
              title: const Text('Napi Jelentés'),
              elevation: 10.0,
              leading: const Icon(Icons.arrow_back_ios_new),
              actions: [
                IconButton(
                    icon: const Icon(Icons.save),
                    tooltip: 'Open shopping cart',
                    onPressed: saveEnabled ? _print("Save Click") : null),
              ]),
          //body: DailyReport(key: _key),
          backgroundColor: Colors.grey[300],
          body: SingleChildScrollView(
              keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
              //itemExtent: 100,
              // shrinkWrap: true,
              child:
              //saveBegin == true
              //  ? _onLoading()
              //: _isData == false

              _isData == false
                  ? SizedBox(
                height: MediaQuery.of(context).size.height / 1.3,
                width: MediaQuery.of(context).size.width,
                child: const Center(
                  child: CircularProgressIndicator(),
                ),
              )
                  : Column(
                //diameterRatio: 10,
                children: <Widget>[
                  Container(
                    padding: const EdgeInsets.all(15),
                    height: 100,
                    child: workUi(),
                  ),
                  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(
                                    2000), //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: TextField(
                        enabled: textMessageEnabled,
                        //keyboardType: TextInputType.multiline,
                        maxLines: null,
                        onSubmitted: (value) => {
                          textMessage = value,
                          (value.length > 3) == true
                              ? _textMessageOK = true
                              : _textMessageOK = false,
                        },

                        //expands: true,
                        textInputAction: TextInputAction.done,
                        decoration: const InputDecoration(
                          border: OutlineInputBorder(),
                          labelText: 'Munkafolyamat leírása',
                        ),
                        /* onChanged: (value) => {
                                    textMessage = value,
                                    (value.length > 3) == true
                                        ? _textMessageOK = true
                                        : _textMessageOK = false,
                                    //myUi.call()
                                  }*/
                      )),
                  //),
                  // The checkboxes will be here
                  Container(
                      padding: const EdgeInsets.only(left: 10, right: 10),
                      child: Card(
                        //elevation: 2,
                          child: ExpandablePanel(
                              header: Container(
                                height: 35,
                                padding: const EdgeInsets.all(5),
                                color: Colors.indigo,
                                child: const Text(
                                  "Jelenlévők kiválasztása",
                                  style: TextStyle(
                                      fontSize: 18,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold),
                                ),
                              ),
                              collapsed:
                              const Text("Érintse a lenyitáshoz."),
                              expanded: AbsorbPointer(
                                absorbing: !_textMessageOK,
                                child: myUi(),
                              )
                            //  tapHeaderToExpand: true,
                            //hasIcon: true,
                          ))
                    /* Column(children: [
                            ListTile(
                              title: const Text(
                                "Jelenlévők",
                                style: TextStyle(fontWeight: FontWeight.bold),
                              ),
                              leading: Icon(Icons.arrow_drop_down_circle),
                              //onTap: ,
                            ),
                            _isData == false
                                ? Center(child: new CircularProgressIndicator())
                                : myUi(),
                          ]),*/
                  ),

                  Container(
                    padding: const EdgeInsets.all(20),
                    child: Center(
                      child: ElevatedButton.icon(
                          onPressed: saveEnabled ? _saveForm : null,
                          icon: const Icon(Icons.save),
                          label: const Text('Save')),
                      // something like 2013-04-20
                      //Text(DateFormat('yyyy.MM.dd').format(selectedDate))
                    ),
                  ),
                ],
              ))));
}
