import 'package:expandable/expandable.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'dart:convert';
import 'package:mobile_portal_23/models/workTimeDetailsModel.dart';
import 'package:mobile_portal_23/classes/common_classes.dart';
import 'package:http/http.dart' as http;
import 'package:jiffy/jiffy.dart';

extension on Duration {
  String format(String s) => '$this'.split('.')[0].padLeft(8, '0');
}

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

late EmployeePageArguments employeePageArguments;
late WorkTimeDetailsModel workTimeList;
bool _isError = false;
bool _isData = false;

final DateFormat nowformat = DateFormat('yyyy.MM');

class _workTimeDetailsState extends State<workTimeDetails> {
  final DateFormat formatter = DateFormat('yyyy MMMM');
  DateTime selectedDate = DateTime.now();

  String appDomain = "iotechnic.eu";
  @override
  void initState() {
    super.initState();
    initializeDateFormatting('hu');

    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) {
      reloadData(nowformat.format(selectedDate));
    });
    //  });
  }

  reloadData(String date) {
    fetchdata(date).then((data) {
      if (data != null) {
        // for (var item in data) {
        workTimeList =
            WorkTimeDetailsModel.fromJson(data); //{'wd': data['wd']}));
        // }

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

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

      // "http://iotechnic.eu/apiGetAllReport/X8B0PQS-2KYMCV3-G5WD74N-8G0CRAH");
        Uri.parse("http://$appDomain/employee/androidAccessList/${employeePageArguments.apiKey!}/$date"));
    //"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: _isData ? Text(formatter.format(selectedDate)) : const Text("ss"),
        elevation: 10.0,
        actions: <Widget>[
          IconButton(
              icon: const Icon(Icons.navigate_before),
              tooltip: 'Show Snackbar',
              onPressed: () {
                selectedDate = Jiffy.parse(selectedDate.toString()).subtract(months: 1).dateTime;
                reloadData(nowformat.format(selectedDate));
              }),
          IconButton(
            icon: const Icon(Icons.navigate_next_rounded),
            color: Colors.white,
            tooltip: 'Go to the next page',
            onPressed: selectedDate.difference(DateTime.now()).inDays < 0
                ? () {
              _isData = false;
              _isError = false;
              selectedDate = Jiffy.parse(selectedDate.toString()).add(months: 1).dateTime;
              // String jiffy=selectedDate.
              reloadData(nowformat.format(selectedDate));
            }
                : null,
          ),
        ],
        // leading: Icon(Icons.arrow_back_ios_new),
      ),
      body: _isData
          ? detailsPage(
          context, workTimeList) //reportCard(context, workTimeList)
          : const Center(child: CircularProgressIndicator()),
      backgroundColor: Colors.grey[300],
    );
  }

  String minToTime(var seconds) {
    int minutes = (seconds / 60).truncate();
    int sec = (seconds % 60);
    String minutesStr = "${minutes.toString().padLeft(2, "0")}.${sec.toString().padLeft(2, "0")}";
    return minutesStr;
  }

  /* Widget _buildContent(BuildContext context) {
    return Container(
        color: Color(0xffECF0F1),
        child: ListView.builder(
          itemCount: workTimeList
              .length, //workTimeList.wd?.length, // The length Of the array

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

          itemBuilder: (context, index) => Container(
              child: //if (_isData)
                  reportCard(context, workTimeList, index)),
        ));
  }*/
  Widget Arrive(e, Wd wtd) {
    var dateformat = DateFormat.E('hu');
    final DateFormat formatter = DateFormat('HH:mm');
    return //Row(crossAxisAlignment: CrossAxisAlignment.center, children: [

      /* Expanded(
          // flex: 1,
          child: Text(
        wtd.date!.substring(8, 11).toString(),
        style: TextStyle(
            fontSize: 16, fontWeight: FontWeight.bold, color: Colors.black87),
      )),
      Expanded(
          //flex: 1,
          child: Text(
        //"$item.month.fullWorkHours",
        wtd.isHoliday == true
            ? dateformat
                .format(DateFormat("yyyy.MM.DD").parse(wtd.date.toString()))
            : dateformat
                .format(DateFormat("yyyy.MM.DD.").parse(wtd.date.toString())),
        //item.month?.fullWorkHours.toString(),
        style: TextStyle(
            fontSize: 16, fontWeight: FontWeight.bold, color: Colors.blue),
      )),*/
      Expanded(
          flex: 8,
          child:
          Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text(
                'É: ${formatter.format(DateFormat("H:mm")
                        .parse(e.start.substring(12, e.start.length)))} ' +
                    e.arriveLoc,
                overflow: TextOverflow.ellipsis),
            if (e.stop == '-')
              const Text('--:--')
            else
              Text(
                  'T: ${formatter.format(DateFormat("H:mm")
                          .parse(e.stop.substring(12, e.stop.length)))} ' +
                      e.getawayLoc,
                  overflow: TextOverflow.ellipsis),
          ]));
  }

  Container startStopWidget(BuildContext context, Wd wtd) {
    var dateformat = DateFormat.E('hu');

    final DateFormat formatter = DateFormat('HH:mm');
    List<Widget> v = [];
    v.add(Expanded(
      // flex: 1,
        child: Text(
          wtd.date!.substring(8, 10).toString(),
          style: const TextStyle(
              fontSize: 16, fontWeight: FontWeight.bold, color: Colors.black87),
        )));
    v.add(
      Expanded(
        //flex: 1,
          child: Text(
            //"$item.month.fullWorkHours",
            wtd.isHoliday == true
                ? dateformat
                .format(DateFormat("yyyy.MM.DD").parse(wtd.date.toString()))
                : dateformat
                .format(DateFormat("yyyy.MM.DD.").parse(wtd.date.toString())),
            //item.month?.fullWorkHours.toString(),
            style: const TextStyle(
                fontSize: 16, fontWeight: FontWeight.bold, color: Colors.blue),
          )),
    );
    if (wtd.isHoliday == false) {
      for (var e in wtd.startStop!) {
        v.add(Expanded(
            flex: 8,
            child:
            Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text(
                  'É: ${formatter.format(DateFormat("yyyy.MM.dd. H:mm")
                          .parse(e.start.toString()))} ${e.arriveLoc}',
                  overflow: TextOverflow.ellipsis),
              if (e.stop == '-')
                const Text('--:--')
              else
                Text(
                    'T: ${formatter.format(DateFormat("yyyy.MM.dd. H:mm")
                            .parse(e.stop.toString()))} ${e.getawayLoc}',
                    overflow: TextOverflow.ellipsis),
            ])));
        debugPrint(wtd.toString());
      }
    }
    return Container(
        color: const Color.fromARGB(255, 206, 206, 206),
        margin: const EdgeInsets.all(10),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: wtd.isHoliday == true
                ? [
              Text(wtd.date.toString()),
              const Text("Szabadság"),
              const Divider(
                thickness: 1.0,
              ),
            ]
                : //wtd.startStop!.map((e) => Arrive(e, wtd)).toList()),
            [
              Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children:
                  v /*[
                          Expanded(
                              // flex: 1,
                              child: Text(
                            wtd.date!.substring(8, 11).toString(),
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Colors.black87),
                          )
                          ),
                          Expanded(
                              //flex: 1,
                              child: Text(
                            //"$item.month.fullWorkHours",
                            wtd.isHoliday == true
                                ? dateformat.format(DateFormat("yyyy.MM.DD")
                                    .parse(wtd.date.toString()))
                                : dateformat.format(DateFormat("yyyy.MM.DD.")
                                    .parse(wtd.date.toString())),
                            //item.month?.fullWorkHours.toString(),
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Colors.blue),
                          )
                          ),

                        wtd.startStop!.map((e) => Arrive(e, wtd)).toList()),
                        ]*/
              )
            ]));
  }

  Container detailsPage(BuildContext context, WorkTimeDetailsModel item) {
    return Container(
        child: ListView.builder(
          itemCount: item.wd!.length,
          itemBuilder: (BuildContext context, int index) {
            _isData = false;
            return //startStopWidget(context, item.wd![index]);
              //reportCard2(context, item.wd![index]);
              buildCard(context, item.wd![index]);
          },
        ));
  }

  Widget buildCard(BuildContext context, Wd itemx) {
    var dayformat = DateFormat.d('hu');
    var dateformat = DateFormat.E('hu');
    final DateFormat formatter = DateFormat('HH:mm');
    return Padding(
      padding: const EdgeInsets.all(10),
      child: Card(
        child: Padding(
            padding: const EdgeInsets.all(10),
            child: ExpandablePanel(
              header: Column(children: [
                Row(
                  children: [
                    Text(
                      itemx.isHoliday == true
                          ? '${dayformat.format(DateFormat("yyyy.MM.dd")
                          .parse(itemx.date.toString()))}.'
                          : '${dayformat.format(DateFormat("yyyy.MM.dd.")
                          .parse(itemx.date.toString()))}.',
                      style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: Colors.black),
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text(
                      //"$item.month.fullWorkHours",
                      itemx.isHoliday == true
                          ? dateformat.format(DateFormat("yyyy.MM.dd")
                          .parse(itemx.date.toString()))
                          : dateformat.format(DateFormat("yyyy.MM.dd.")
                          .parse(itemx.date.toString())),
                      //item.month?.fullWorkHours.toString(),
                      style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: Colors.blue),
                    ),
                  ],
                ),
                const Divider(
                  color: Colors.blue,
                  thickness: 1,
                )
              ]),
              //Text("Header"),

              collapsed: //Text('collapsed'),
              itemx.isHoliday == true
                  ? const Text("Szabadság")
                  : Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Row(
                        mainAxisAlignment:
                        MainAxisAlignment.spaceBetween,
                        children: [
                          //Text(itemx.fullHours.toString()),

                          Text('Normál óra'),
                          Text('Túlóra óra'),
                          Text('Összes óra'),
                        ]),
                    Row(
                        mainAxisAlignment:
                        MainAxisAlignment.spaceAround,
                        children: [
                          Text(
                              formatter.format(DateFormat("mm")
                                  .parse(itemx.hours.toString())),
                              textAlign: TextAlign.center),
                          Text(
                              formatter.format(DateFormat("mm")
                                  .parse(itemx.overTime.toString())),
                              textAlign: TextAlign.center),
                          Text(
                              formatter.format(DateFormat("mm")
                                  .parse(itemx.fullHours.toString())),
                              textAlign: TextAlign.center),
                        ]),
                  ]),
              expanded: itemx.isHoliday == true
                  ? const Text("Szabadság")
                  : Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    const Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          //Text(itemx.fullHours.toString()),

                          Text('Érkezés'),
                          Text('Távozás'),
                          Text('Óra'),
                        ]),
                    Column(
                        children: itemx.startStop!
                            .map<Widget>((e) => _getrow(e))
                            .toList())
                  ]),
            )),
      ),
    );
  }

  Widget _getrow(StartStop e) {
    final DateFormat formatter = DateFormat('HH:mm');
    var start = DateFormat("yyyy.MM.dd. HH:mm").parse(e.start.toString());
    DateTime stop=DateTime(2024);
    late Duration diff;
    if (e.stop != '-') {
      stop = DateFormat("yyyy.MM.dd. HH:mm").parse(e.stop.toString());
      diff = stop.difference(start);
    }
    return Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
      Text(formatter.format(start), textAlign: TextAlign.center),
      if (e.stop == '-') ...[
        const Text('--:--'),
        const Text('--:--')
      ] else ...[
        Text(formatter.format(stop), textAlign: TextAlign.center),
        Text(
            formatter.format(DateFormat("mm").parse(diff.inMinutes.toString())),
            textAlign: TextAlign.center),
      ]
    ]);
  }

  Card reportCard2(BuildContext context, Wd itemx) {
    var dateformat = DateFormat.E('hu');
    final DateFormat formatter = DateFormat('HH:mm');
    return Card(
        child: Padding(
            padding: const EdgeInsets.all(15.0),
            child:
            Column(mainAxisAlignment: MainAxisAlignment.center, children: [
              Expanded(
                  flex: 1,
                  child: Text(
                    //"$item.month.fullWorkHours",
                    itemx.isHoliday == true
                        ? dateformat.format(DateFormat("yyyy.MM.dd")
                        .parse(itemx.date.toString()))
                        : dateformat.format(DateFormat("yyyy.MM.dd.")
                        .parse(itemx.date.toString())),
                    //item.month?.fullWorkHours.toString(),
                    style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: Colors.blue),
                  )),
              const Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                //Text(itemx.fullHours.toString()),

                Text('Normál óra'),
                Text('Túlóra óra'),
                Text('Összes óra'),
              ]),
              Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
                Text(
                    formatter
                        .format(DateFormat("mm").parse(itemx.hours.toString())),
                    textAlign: TextAlign.center),
                Text(
                    formatter.format(
                        DateFormat("mm").parse(itemx.overTime.toString())),
                    textAlign: TextAlign.center),
                Text(
                    formatter.format(
                        DateFormat("mm").parse(itemx.fullHours.toString())),
                    textAlign: TextAlign.center),
              ]),
            ])));
  }

  Card reportCard(BuildContext context, WorkTimeDetailsModel itemx) {
    int workHour = 0;
    bool workOpened = false;
    //bool? isHoliday = item.wd![index].isHoliday;
    var dateformat = DateFormat.E('hu');
    return Card(
      clipBehavior: Clip.antiAlias,
      child: ListView.builder(
        itemCount: itemx.wd?.length,
        itemBuilder: (BuildContext context, int index) {
          List<Text> start = itemx.wd![index].isHoliday != true
              ? itemx.wd![index].startStop!
              .map(
                (e) => Text(
              e.start.toString(),
              //item.dailyReport[0].workTitle!,
              style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.black.withOpacity(0.6)),
            ),
          )
          //.cast<StartStop>()
              .toList()
              : [const Text("Szabi")];
          bool? isHoliday = itemx.wd![index].isHoliday;
          return ListTile(
              leading: CircleAvatar(
                backgroundColor: Colors.blue,
                child: Text(
                  //"$item.month.fullWorkHours",
                  isHoliday == true
                      ? dateformat.format(DateFormat("yyyy.MM.DD")
                      .parse(itemx.wd![index].date.toString()))
                      : dateformat.format(DateFormat("yyyy.MM.DD.")
                      .parse(itemx.wd![index].date.toString())),
                  //item.month?.fullWorkHours.toString(),
                  style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.white),
                ),
              ),
              title: isHoliday == false
                  ? Column(children: [
                Row(
                    children:
                    start /*itemx.wd![index].startStop!
                            .map(
                              (e) => Text(
                                e.start.toString(),
                                //item.dailyReport[0].workTitle!,
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.black.withOpacity(0.6)),
                              ),
                            )
                            .toList(),*/
                ),
                const Divider(
                  thickness: 1.0,
                ),
              ])
                  : const Text("Szabi"));
          //Text(itemx.wd![index].date.toString());
        },
      ),
      /*Column(
        children: [
          ListTile(
              tileColor: Colors.blue,
              onTap: () {},
              leading: CircleAvatar(
                  backgroundColor: Colors.white,
                  child: Text(
                    //"$item.month.fullWorkHours",
                    isHoliday == true
                        ? dateformat.format(DateFormat("yyyy.MM.DD")
                            .parse(item.wd![index].date.toString()))
                        : dateformat.format(DateFormat("yyyy.MM.DD.")
                            .parse(item.wd![index].date.toString())),
                    //item.month?.fullWorkHours.toString(),
                    style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: Colors.blue),
                  )),
              title: Text(
                item.wd?[index].date as String,
                style: TextStyle(color: Colors.white),
              ),
              subtitle: isHoliday == true
                  ? Text(
                      "Szabadság",
                      style: TextStyle(
                          color: Colors.yellow,
                          fontWeight: FontWeight.bold,
                          fontSize: 18),
                    )
                  : item.wd![index].notes != null
                      ? Text(
                          item.wd![index].notes as String,
                          style:
                              TextStyle(color: Colors.black.withOpacity(0.6)),
                        )
                      : Text("Nincs")),
          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: ' +
                        Duration(minutes: item.month!.fullWorkHours!.toInt())
                            .format(),
                    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: [
                  Text(
                    item.wd![index].date.toString(),
                    //item.dailyReport[0].workTitle!,
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.black.withOpacity(0.6)),
                  ),
                ]
                    /*   .map(
                        (e) => Text(
                          e.date.toString(),
                          //item.dailyReport[0].workTitle!,
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.black.withOpacity(0.6)),
                        ),
                      )
                      .toList(),*/
                    ),
                Divider(
                  thickness: 1.0,
                ),
              ]))),
        ],
      ),*/
    );
  }

/*
  Widget _buildContent(BuildContext context) {
    return Container(
        color: Color(0xffECF0F1),
        child: ListView.builder(
          itemCount: workTimeList.wd?.length, // The length Of the array

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

          itemBuilder: (context, index) => Container(
              child: //if (_isData)
                  reportCard(context, workTimeList, index)),
        ));
  }
*/

/*  Card reportCard(BuildContext context, WorkTimeDetailsModel item, int index) {
    int workHour = 0;
    bool workOpened = false;
    bool? isHoliday = item.wd![index].isHoliday;
    var dateformat = new DateFormat.E('hu');
    return Card(
      clipBehavior: Clip.antiAlias,
      child: Column(
        children: [
          ListTile(
              tileColor: Colors.blue,
              onTap: () {},
              leading: CircleAvatar(
                  backgroundColor: Colors.white,
                  child: Text(
                    //"$item.month.fullWorkHours",
                    isHoliday == true
                        ? dateformat.format(DateFormat("yyyy.MM.DD")
                            .parse(item.wd![index].date.toString()))
                        : dateformat.format(DateFormat("yyyy.MM.DD.")
                            .parse(item.wd![index].date.toString())),
                    //item.month?.fullWorkHours.toString(),
                    style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: Colors.blue),
                  )),
              title: Text(
                item.wd?[index].date as String,
                style: TextStyle(color: Colors.white),
              ),
              subtitle: isHoliday == true
                  ? Text(
                      "Szabadság",
                      style: TextStyle(
                          color: Colors.yellow,
                          fontWeight: FontWeight.bold,
                          fontSize: 18),
                    )
                  : item.wd![index].notes != null
                      ? Text(
                          item.wd![index].notes as String,
                          style:
                              TextStyle(color: Colors.black.withOpacity(0.6)),
                        )
                      : Text("Nincs")),
          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: ' +
                        Duration(minutes: item.month!.fullWorkHours!.toInt())
                            .format(),
                    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: [
                  Text(
                    item.wd![index].date.toString(),
                    //item.dailyReport[0].workTitle!,
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.black.withOpacity(0.6)),
                  ),
                ]
                    /*   .map(
                        (e) => Text(
                          e.date.toString(),
                          //item.dailyReport[0].workTitle!,
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.black.withOpacity(0.6)),
                        ),
                      )
                      .toList(),*/
                    ),
                Divider(
                  thickness: 1.0,
                ),
              ]))),
        ],
      ),
    );
  }*/
}
