import 'package:flutter/foundation.dart';
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 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

String appDomain = "iotechnic.eu";

class ReportCreate extends StatefulWidget {
  const ReportCreate({Key? key}) : super(key: key);
  static const routeName = '/reportNew';
  @override
  State<ReportCreate> createState() => _ReportCreateState();
}
late EmployeePageArguments employeePageArguments;
late ReportArguments reportArguments;

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);
  if (kDebugMode) {
    print(resp.toString());
  }

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


class _ReportCreateState extends State<ReportCreate> {
  final _formKey = GlobalKey<FormState>();
  late List<String> favoriteWorks = [];
  bool _isError = false;
  bool _isData = false;
  final bool _showFaworites = false;
  bool _nextEnable=false;
  List<EmployeeLs> employeeList = [];
  late ReportArguments reportArgs=new ReportArguments([], "", "", false);
  late List<WorkListModel> workList = [];
  int employeeCount=0;
  // late EmployeeArguments empArgs;

  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;
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final args = ModalRoute.of(context)!.settings.arguments as Map;

      employeePageArguments = args['userArgs'];
      //reportArguments = args['dataArgs'];
      fetchData(employeePageArguments.apiKey!).then((value) {
        setState(() {
          employeeList.addAll(value);
          employeeList.sort((a,b)=>a.name.compareTo(b.name));
          _isData = true;
        });
      });
    });
    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();
  }
  int currentStep = 0;
  @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'];
    return Scaffold(
      //resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title: const Text("Új jelentés"),
          actions: [
            IconButton(
              icon: const Icon(Icons.search),
              onPressed: () {},
            ),

          ],
          actionsIconTheme: const IconThemeData(
            size: 32,
          ),
        ),
        //drawer: Drawer(),

        body:  page(context),

       /* bottomNavigationBar: BottomAppBar(
          color: Colors.cyan,
          child: Container(
            height: 50.0,
          ),

        )*/

    );
    //visible: _enableSave,


  }

  Widget page(BuildContext context) {


    _nextEnable=false;
  switch(currentStep){
    case 0:
      if (reportArgs.workId.isNotEmpty) {
        _nextEnable=true;
      }
      break;
    case 1:
      if (reportArgs.workId.isNotEmpty && employeeCount>0) {
        _nextEnable=true;
      }
      break;
  }

    return  Container(
        padding: const EdgeInsets.all(1),
        child: Stepper(
          type: StepperType.vertical,
          currentStep: currentStep,
          onStepCancel: () => currentStep == 0
              ? null
              : setState(() {
            currentStep -= 1;
          }),

          onStepContinue: _nextEnable ?() {
            bool isLastStep = (currentStep == getSteps(context).length - 1);

            if (isLastStep) {
              //Do something with this information
            } else {
              setState(() {
                currentStep += 1;
              });
            }
          }
          :null,
          onStepTapped: (step) => setState(() {
            currentStep = step;
          }),
          steps: getSteps(context),
        ),
    );
  }

  List<Step> getSteps(BuildContext ctx) {
    return <Step>[
      Step(
        state: currentStep > 0 ? StepState.complete : StepState.indexed,
        isActive: currentStep >= 0,
        title: const Text("Munka kiválasztása"),
        content: selectWork(ctx)
      ),
      Step(
        state: currentStep > 1 ? StepState.complete : StepState.indexed,
        isActive: currentStep >= 1,
        title: const Text("Address"),
        content: empList(context),
      ),
      Step(
        state: currentStep > 2 ? StepState.complete : StepState.indexed,
        isActive: currentStep >= 2,
        title: const Text("Misc"),
        content: const Column(
          children: [
            Text("Ibrányi"),
          ],
        ),
      ),
    ];
  }


  Container selectWork(BuildContext ctx) {
    return _isData == false
        ? _isError
        ? Container(
      height:MediaQuery
          .of(ctx)
          .size
          .height / 1.6,
      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(ctx)
              .size
              .height / 1.6,
          width: MediaQuery
              .of(ctx)
              .size
              .width,
          child: const Center(
            child: CircularProgressIndicator(),
          ),
        ))
        : gridList(context);
  }

  Container gridList(BuildContext ctx) {
    //List<ModelReportList> _reportList = [];
    List<WorkListModel> workListl = [];
    if (_showFaworites) {
      workListl = workList
          .where((element) => favoriteWorks.contains(element.sId))
          .toList();
    } else {
     workListl = workList;
    }
    return Container(

      height:MediaQuery
          .of(ctx)
          .size
          .height / 1.6,
      //color: const Color(0xffECF0F1),
      child: ListView.builder(
        itemCount: workListl.length, // The length Of the array
        scrollDirection: Axis.vertical,
        padding: const EdgeInsets.all(1),
        shrinkWrap: true,

        itemBuilder: (ctx, index) => //Container(
         // child:
          reportCard(ctx, workListl[index]),
       // ),
      ),
    );
  }
  Card reportCard(BuildContext ctx, 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, color: Colors.yellow)),
            onTap: workOpened
                ? () {
              setState(() {
               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)),
                      ),
                    ]),
                  ]))),
        ],
      ),
    );
  }

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

    return Container(
      height:MediaQuery
          .of(context)
          .size
          .height / 1.6,
      color: Colors.white,
      child: ListView.builder(
        itemCount: employeeList.length, // The length Of the array
        scrollDirection: Axis.vertical,
        padding: const EdgeInsets.all(1),
        shrinkWrap: true,

        itemBuilder: (context, index) => Container(
          child: Column(children: [
            employeeWidget(context, index),
            const Divider(
              thickness: 1.0,
            ),
          ],)
        ),
      ),
    );
  }

  SwitchListTile employeeWidget(BuildContext context, index) {
    return SwitchListTile(
      //controlAffinity: ListTileControlAffinity.trailing,
        activeColor: Colors.green,
        value: employeeList[index].value,
        title: Text(employeeList[index].name, style: const TextStyle(fontSize: 18),),

        onChanged: (newValue) {
          setState(() {
            employeeList[index].value = newValue;
            employeeCount=0;
            for (var hobby in employeeList) {
              if (hobby.value == true) {
                //print(hobby.name);
                employeeCount++;
              }
            };
            //checkize();
          });
        });
  }
}


