import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hris_selfservice_mobile/Screens/Menu/AjukanCuti/RequestHttp/historyCuti_post.dart';
import 'package:progress_dialog_null_safe/progress_dialog_null_safe.dart';
import 'dart:developer' as logDev;

import '../AjukanCuti/backgroundHistory.dart';

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

  @override
  State<HistoryCuti> createState() => _HistoryCutiState();
}

class _HistoryCutiState extends State<HistoryCuti> {
  late List <String> id_List;
  late List <String> name_List;
  late List <String> type_cuti_List;
  late List <String> detail_List;
  late List <String> created_on_List;
  late List <String> created_by_List;
  late List <String> start_date_List;
  late List <String> end_date_List;
  late List <String> duration_List;
  late List <String> status_List;
  late List <Color> statusColor;
  late List <bool> visible;

  int HistoryLength = 0;

  @override
  initState() {
    super.initState();
    id_List = [""];
    name_List = [""];
    type_cuti_List = [""];
    detail_List = [""];
    created_on_List = [""];
    created_by_List = [""];
    start_date_List = [""];
    end_date_List = [""];
    duration_List = [""];
    status_List = [""];
    statusColor = [Colors.black54];
    visible = [false];

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      getHistoryData();
    });
    logDev.log(HistoryLength.toString(), name: "Banyak History");
  }

  getHistoryData() async {
    ProgressDialog loading = ProgressDialog(context);
    loading = ProgressDialog(context,
        type: ProgressDialogType.normal, isDismissible: false, showLogs: true);
    loading.style(
        message: 'Please Wait .....',
        borderRadius: 3,
        backgroundColor: Colors.white,
        progressWidget: CircularProgressIndicator(),
        elevation: 10.0,
        padding: EdgeInsets.all(10),
        insetAnimCurve: Curves.easeInOut,
        progress: 0.0,
        maxProgress: 100.0,
        progressTextStyle: TextStyle(
            color: Colors.black, fontSize: 10.0, fontWeight: FontWeight.w400),
        messageTextStyle: TextStyle(
            color: Colors.black, fontSize: 15.0, fontWeight: FontWeight.w600));

    loading.show();
    HistoryCuti_Post.connectToAPI().then((valueResult) async {
      Map<String, dynamic> object = jsonDecode(valueResult);
      if (object.containsKey("result").toString() == "true") {
        String result = object['result'].toString();
        if (result.contains("Failed")) {
          loading.hide();
          alertDialogFailedRetrievedData(context);
        } else {
          List <dynamic> historyCuti = object['result'];
         /* logDev.log(historyCuti.toString(), name: "History Cuti");
          logDev.log(historyCuti.length.toString(), name: "Banyaknya History Cuti");*/
          setState(() {
            for (int i = 0; i < historyCuti.length; i++){
              String id = historyCuti[i]['id'].toString();
              String name = historyCuti[i]['name'].toString();
              String type_cuti = historyCuti[i]['type_cuti'].toString();
              String detail = historyCuti[i]['detail'].toString();
              String created_on = historyCuti[i]['created_on'].toString();
              String created_by = historyCuti[i]['created_by'].toString();
              String start_date = historyCuti[i]['start_date'].toString();
              String end_date = historyCuti[i]['end_date'].toString();
              String duration = historyCuti[i]['duration'].toString();
              String status = historyCuti[i]['status'].toString();

              if (detail == "false"){
                detail = "-";
              }

              id_List.add(id);
              name_List.add(name);
              type_cuti_List.add(type_cuti);
              detail_List.add(detail);
              created_on_List.add(created_on);
              created_by_List.add(created_by);
              start_date_List.add(start_date.substring(0,10));
              end_date_List.add(end_date.substring(0,10));
              duration_List.add(duration);
              status_List.add(status);
              visible.add(false);

              var statColor;
              if (status == "To Approve"){
                statColor = Colors.red;
              } else if (status == "Second Approval"){
                statColor = Colors.green;
              } else if (status == "Approved"){
                statColor = Colors.blueAccent;
              }
              statusColor.add(statColor);
            }

            id_List.removeAt(0);
            name_List.removeAt(0);
            type_cuti_List.removeAt(0);
            detail_List.removeAt(0);
            created_on_List.removeAt(0);
            created_by_List.removeAt(0);
            start_date_List.removeAt(0);
            end_date_List.removeAt(0);
            duration_List.removeAt(0);
            status_List.removeAt(0);
            statusColor.removeAt(0);
            visible.removeAt(0);

            HistoryLength = historyCuti.length;
          });
          loading.hide();
        }
      } else {
        Fluttertoast.showToast(
            msg: "Server Response Error",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            textColor: Colors.white,
            fontSize: 16.0);
      }
    });
    loading.hide();
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    return Scaffold(
      body: Stack(
          children: [
            Column(
              children: <Widget>[
                Stack(
                  children: [
                    WavyHeader(),
                    Container(
                        margin: EdgeInsets.only(top: (size.height / 6) - 20),
                        padding: EdgeInsets.fromLTRB(0, 5, 25, 5),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Text(
                              'Time Off History\t\t',
                              maxLines: 1,
                              style: GoogleFonts.luckiestGuy(
                                fontSize: 28,
                                color: Color(0xFF4858A7),
                                fontStyle: FontStyle.italic,
                              ),
                            ),
                            Image.asset(
                              'assets/images/ic_history.png',
                              width: 40,
                              height: 40,
                            ),
                          ],
                        )
                    ),
                  ],
                ),
              ],
            ),
            Container(
              margin: EdgeInsets.only(top: (MediaQuery.of(context).size.height / 6) + 40, left: 5, right: 5, bottom: 10),
              child: ListView.builder(
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: HistoryLength,
                itemBuilder: (context, int i) {
                  return Container(
                    child: InkWell(
                      child: Card(
                        elevation: 10,
                        child: Column(
                          children: [
                            Row(
                              children: [
                                Expanded(
                                    flex: 8,
                                    child: Padding(
                                      padding: EdgeInsets.fromLTRB(10, 5, 5, 5),
                                      child: Column(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(type_cuti_List[i], style: GoogleFonts.rubikBubbles(fontSize: 16)),
                                          Text(start_date_List[i] + " - " + end_date_List[i] + " (" + duration_List[i] + ") ", style: GoogleFonts.nunito(fontSize: 15)),
                                          Text("\nDescription : " + detail_List[i], style: GoogleFonts.nunito(fontSize: 15)),
                                          Text("\nCreated : " + created_on_List[i], style: GoogleFonts.yeonSung(fontSize: 14, fontStyle: FontStyle.italic)),
                                        ],
                                      ),
                                    )
                                ),
                                Expanded(
                                    flex: 2,
                                    child: Padding(
                                      padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
                                      child: Text(status_List[i], textAlign: TextAlign.center, style: GoogleFonts.lilitaOne(color: statusColor[i], fontSize: 17),
                                      ),
                                    )
                                ),
                              ],
                            ),
                            Align(
                              alignment: Alignment.centerLeft,
                              child: Visibility(
                                  visible: visible[i],
                                  child: Padding(
                                    padding: EdgeInsets.fromLTRB(10, 5, 5, 5),
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text("\nAttachment : ", style: GoogleFonts.josefinSans(fontSize: 15, fontWeight: FontWeight.bold)),
                                        Text("Created : " + created_on_List[i], style: GoogleFonts.nunito(fontSize: 15, fontStyle: FontStyle.italic)),
                                      ],
                                    ),
                                  )
                              ),
                            )
                          ],
                        ),
                      ),
                      onTap: (){
                        setState(() {
                          visible[i] = !visible[i];
                        });
                      },
                    ),
                  );
                },
              ),
            )
          ]),
    );
  }
}

alertDialogFailedRetrievedData(BuildContext context) {
  Widget okButton = TextButton(
    child: Text("Refresh"),
    onPressed: () {
      Navigator.of(context, rootNavigator: true).pop();
      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (context) => HistoryCuti()));
    },
  );

  Widget noButton = TextButton(
    child: Text("Back"),
    onPressed: () {
      Navigator.of(context, rootNavigator: true).pop();
      Navigator.pop(context);
    },
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("Employee Self Service"),
    content: Text("Failed to Retrieve Data"),
    actions: [
      noButton,
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}