import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:get/get.dart';
import 'package:mwf_app/home.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/convert.dart';
import 'package:mwf_app/service/fontsize.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/shadow.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/model/TodoList_model.dart';
import 'package:mwf_app/set1/task_list.dart';
import 'package:mwf_app/set1/task_list_edit.dart';
import 'package:need_resume/need_resume.dart';

class Schedule extends StatefulWidget {
  String id = "Schedule";
  @override
  _ScheduleState createState() => _ScheduleState();
}

class _ScheduleState extends ResumableState<Schedule> {
  bool isLoaddata = false;
  bool isLoading = false;
  bool isData = true;
  bool activeWeek = false;
  bool activeMonth = false;
  bool activeAll = false;
  String textWarning = "";
  String setText = "";
  @override
  void initState() {
    super.initState();
    print("init");
    loadWeekData(); // ดึงข้อมูล
    setState(() {
      activeWeek = true;
      activeMonth = false;
      activeAll = false;
      isData = checkData(TodoList.data, "ในสัปดาห์นี้") ? true : false;
    });
  }

  @override
  void onReady() {
    print('Screen is ready!');
  }

  @override
  void onResume() {
    print('Screen is resumed! Todolist ');
    setState(() {
      if (setText == "ทั้งหมด") {
        activeWeek = false;
        activeMonth = false;
        activeAll = true;
        isData = checkData(TodoList.data, "ไม่มีข้อมูล") ? true : false;
        loadData();
      } else if (setText == "สัปดาห์นี้") {
        activeWeek = true;
        activeMonth = false;
        activeAll = false;
        isData = checkData(TodoList.data, "ในสัปดาห์นี้") ? true : false;
        loadWeekData(); // ดึงข้อมูล
      } else if (setText == "เดือนนี้") {
        activeWeek = false;
        activeMonth = true;
        activeAll = false;
        isData = checkData(TodoList.data, "ในเดือนนี้") ? true : false;
        loadWeekMonthData(); // ดึงข้อมูล
      }
    });
  }

  loadData() async {
    try {
      buttonActive(false, false, true);
      isLoading = true;
      final list = await TodoList.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      checkData(list, "");
      setState(() {
        int i = 0;
        TodoList.data.clear();
        list.forEach((v) {
          i+=1;
          final scheduleList = TodoList.fromJson(v);
          // if(scheduleList.packageType != "")
          //   print(i.toString() + " -- " + scheduleList.packageType);
          TodoList.data.add(scheduleList); // loop เก็บข้อมูล
          TodoList.data.sort((a, b) => a.startdate.compareTo(b.startdate));
        });
        print(list);
      });
      isLoading = false;
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
    }
  }

  buttonActive(week, month, all) {
    setState(() {
      activeWeek = week;
      activeMonth = month;
      activeAll = all;
    });
  }

  loadWeekMonthData() async {
    try {
      buttonActive(false, true, false);
      isLoading = true;
      final list = await TodoList.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      setState(() {
        TodoList.data.clear();
        DateTime schDate;
        int n = DateTime.now().month;
        int y = DateTime.now().year;
        int i = 0;
        list.forEach((v) {
          i+=1;
          final scheduleList = TodoList.fromJson(v);
          schDate = DateTime.parse(scheduleList.startdate);
          if (schDate.month == n && schDate.year == y) {
            // if(scheduleList.packageType != "")
            //   print(i.toString() + " -- " + scheduleList.packageType);
            TodoList.data.add(scheduleList); // loop เก็บข้อมูล
            TodoList.data.sort((a, b) => a.startdate.compareTo(b.startdate));
            checkData(TodoList.data, "ในเดือนนี้");
          }
        });
      });
      isLoading = false;
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
    }
  }

  loadWeekData() async {
    try {
      buttonActive(true, false, false);
      isLoading = true;
      final list = await TodoList.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api

      setState(() {
        TodoList.data.clear();
        var calc = 7 - DateTime.now().weekday;
        var lastDayOfWeek = DateTime.parse(DateTime.now()
            .add(new Duration(days: calc))
            .toString()
            .substring(0, 10));

        DateTime date;
        DateTime firstOfWeek = DateTime.parse(DateTime.now()
            .add(new Duration(days: -DateTime.now().weekday + 1))
            .toString()
            .substring(0, 10));
        int i = 0;
        list.forEach((v) {
          i+=1;
          final scheduleList = TodoList.fromJson(v);
          date = DateTime.parse(
              scheduleList.startdate.toString().substring(0, 10));
          if ((date.isAfter(firstOfWeek) || date == firstOfWeek) &&
              (date.isBefore(lastDayOfWeek) || date == lastDayOfWeek)) {
            // if(scheduleList.packageType != "")
            //   print(i.toString() + " -- " + scheduleList.packageType);
            TodoList.data.add(scheduleList); // loop เก็บข้อมูล
            TodoList.data.sort((a, b) => a.startdate.compareTo(b.startdate));
            checkData(TodoList.data, "ในสัปดาห์นี้");
          }
        });
      });
      isLoading = false;
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
      throw e;
    }
  }

  Future<List<TodoList>> _getDataWeek() async {
    try{
      buttonActive(true, false, false);
      isLoading = true;
      final list = await TodoList.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api

      setState(() {
        TodoList.data.clear();
        var calc = 7 - DateTime.now().weekday;
        var lastDayOfWeek = DateTime.parse(DateTime.now()
            .add(new Duration(days: calc))
            .toString()
            .substring(0, 10));

        DateTime date;
        DateTime firstOfWeek = DateTime.parse(DateTime.now()
            .add(new Duration(days: -DateTime.now().weekday + 1))
            .toString()
            .substring(0, 10));
        int i = 0;
        list.forEach((v) {
          i+=1;
          final scheduleList = TodoList.fromJson(v);
          date = DateTime.parse(
              scheduleList.startdate.toString().substring(0, 10));
          if ((date.isAfter(firstOfWeek) || date == firstOfWeek) &&
              (date.isBefore(lastDayOfWeek) || date == lastDayOfWeek)) {
            // if(scheduleList.packageType != "")
            //   print(i.toString() + " -- " + scheduleList.packageType);
            TodoList.data.add(scheduleList); // loop เก็บข้อมูล
            TodoList.data.sort((a, b) => a.startdate.compareTo(b.startdate));
            checkData(TodoList.data, "ในสัปดาห์นี้");
          }
        });
      });
    }catch(e){
      print(e);
    }
    return TodoList.data;
  }

  checkData(list, String warning) {
    if (list.isNotEmpty) {
      setState(() {
        isData = true;
      });
    } else {
      setState(() {
        textWarning = warning;
        isData = false;
      });
    }
    return isData;
  }

  @override
  Widget build(BuildContext context) {
    Header.currentPage = "schedule";
    Header.routes = HomePage();
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }

    double _width = MediaQuery.of(context).size.width;

    Widget _btnAll = _buildButton(
        context, "ทั้งหมด", Colors.purple[300], Colors.white, activeAll);

    Widget _btnWeek = _buildButton(
        context, "สัปดาห์นี้", Colors.purple[300], Colors.white, activeWeek);

    Widget _btnMonth = _buildButton(
        context, "เดือนนี้", Colors.purple[300], Colors.white, activeMonth);

    return Material(
      color: AppColors.bgColor,
      child:  WillPopScope(
        onWillPop: () async {
          Get.offAll(Header.routes);
          return false;
        },
        child: Stack(
          children: <Widget>[
            Header.header2ListPage(context),
            Header.mainMenu(context),
            Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(
                    bottom: mediaQuery(context, 'h', 20),
                    top: mediaQuery(context, 'h', 400),
                  ),
                  padding: EdgeInsets.only(
                      left: mediaQuery(context, 'w', 60),
                      right: mediaQuery(context, 'w', 60)),
                  child: Column(
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            // header text
                            AppStrings.menu_schedule,
                            style: TextStyle(
                              color: Color(0xFFB58E38),
                              fontSize:
                                  mediaQuery(context, 'h', AppFontSize.headText),
                            ),
                          )
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Expanded(
                            child: _btnWeek,
                          ),
                          SizedBox(
                            width: 3,
                          ),
                          Expanded(
                            child: _btnMonth,
                          ),
                          SizedBox(
                            width: 3,
                          ),
                          Expanded(
                            child: _btnAll,
                          ),
                          Container(
                            width: mediaQuery(context, 'w', 1),
                          ),
                          SizedBox(
                            width: 2,
                          ),
                          GestureDetector(
                            onTap: () {
                              print('click Add TaskList');
                              push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => TaskList()),
                              );
                            },
                            child: Row(
                              children: <Widget>[
                                Icon(
                                  Icons.add_circle_outline,
                                  size: mediaQuery(context, 'h', 80),
                                  color: AppColors.color,
                                ),
                                SizedBox(
                                  width: mediaQuery(context, 'w', 14),
                                ),
                                Text(
                                  AppStrings.addTask,
                                  style: TextStyle(
                                    color: AppColors.color,
                                    fontSize:
                                        mediaQuery(context, 'h', AppFontSize.btn),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
                Container(
                  width: _width,
                  height: mediaQuery(context, 'h', 1550),
                  margin: EdgeInsets.only(
                    left: mediaQuery(context, 'w', 60),
                    right: mediaQuery(context, 'w', 60),
                  ),
                  child: isData
                      ? ListView(
                          scrollDirection: Axis.vertical,
                          shrinkWrap: true,
                          padding: EdgeInsets.only(
                            top: mediaQuery(context, 'h', 1),
                          ),
                          children: list(_width),
                        )
                      : _noData(context, textWarning),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> list(double width) {
    List<Widget> list = new List();
    var num = 1;
    String detailTask = "";
    for (var i = 0; i < TodoList.data.length.toInt(); i++) {
      String detail = "";
      String title = "";
      String name = "";
      if(TodoList.data[i].packageType == "PackageRequest"){
        if(TodoList.data[i].detail.isNotEmpty){
          detail = TodoList.data[i].detail.split(" ")[0];
          title = TodoList.data[i].detail.split(" ")[1];
          name = TodoList.data[i].detail.split(" ")[2];
          detailTask = detail + "\n" + title + "\n" + name;
        }else{
          detailTask = "";
        }
      }
      list.add(
        Container(
          width: mediaQuery(context, 'w', 1005),
          padding: EdgeInsets.all(
            mediaQuery(context, 'h', 50),
          ),
          margin: EdgeInsets.only(
            bottom: mediaQuery(context, 'h', 40),
          ),
          decoration: BoxDecoration(
            borderRadius: new BorderRadius.all(
              Radius.circular(
                mediaQuery(context, 'h', 20),
              ),
            ),
            boxShadow: [
              appShadow(),
            ],
            color: Colors.white,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Container(
                width: mediaQuery(context, 'w', 800),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Text(
                          'ลำดับ : ',
                          style: TextStyle(
                            color: AppColors.color_text,
                            fontSize: mediaQuery(context, 'h', 50),
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Flexible(
                          child: Text(
                            num.toString(),
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 50),
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'รายละเอียด : ',
                          style: TextStyle(
                            color: AppColors.color_text,
                            fontSize: mediaQuery(context, 'h', 40),
                          ),
                        ),
                        Flexible(
                          child: Text( 
                            // TodoList.data[i].detail.trim(),
                            TodoList.data[i].packageType == "PackageRequest" ? detailTask : TodoList.data[i].detail.trim(),
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        Text(
                          'วันที่เริ่มต้น : ',
                          style: TextStyle(
                            color: Color(0xFF8B939A),
                            fontSize: mediaQuery(context, 'h', 40),
                          ),
                        ),
                        Flexible(
                          child: Text(
                            AppConvert.date(TodoList.data[i].startdate) +
                                " " +
                                AppConvert.time(TodoList.data[i].startdate) +
                                " น.",
                            style: TextStyle(
                              color: Color(0xFF8B939A),
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        Text(
                          'วันที่สิ้นสุด : ',
                          style: TextStyle(
                            color: Color(0xFF8B939A),
                            fontSize: mediaQuery(context, 'h', 40),
                          ),
                        ),
                        Flexible(
                            child: (TodoList.data[i].enddate != null &&
                                    TodoList.data[i].enddate !=
                                        '0001-01-01T00:00:00')
                                ? Text(
                                    AppConvert.date(TodoList.data[i].enddate) +
                                        " " +
                                        AppConvert.time(
                                            TodoList.data[i].enddate) +
                                        " น.",
                                    style: TextStyle(
                                      color: Color(0xFF8B939A),
                                      fontSize: mediaQuery(context, 'h', 40),
                                    ),
                                  )
                                : Text(
                                    " - ",
                                    style: TextStyle(
                                      color: Color(0xFF8B939A),
                                      fontSize: mediaQuery(context, 'h', 40),
                                    ),
                                  )),
                      ],
                    ),
                  ],
                ),
              ),
              TodoList.data[i].readFlag == true &&
              (TodoList.data[i].packageType != "PackageRequest" &&
              TodoList.data[i].packageType == "TodoList" &&
              TodoList.data[i].packageType != "")
                  ? Flexible(
                      child: Column(
                        children: <Widget>[
                          ClipOval(
                            child: Material(
                              color: Colors.transparent, // button color
                              child: InkWell(
                                splashColor: AppColors.color, // inkwell color
                                child: SizedBox(
                                  width: mediaQuery(context, 'w', 90),
                                  height: mediaQuery(context, 'h', 90),
                                  child: Icon(FontAwesomeIcons.pencilAlt,
                                      color: AppColors.color, size: 21.1),
                                ),
                                onTap: () {
                                  print('click TaskListEdit');
                                  print(TodoList.data[i].todolistID);
                                  AppLoader.showError("ไม่สามารถเชื่อมต่อได้");
                                  AppLoader.hide();
                                  if (TodoList.data[i].todolistID.length > 0) {
                                    push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => TaskListEdit(
                                              TodoList.data[i].todolistID)),
                                    );
                                  } else {
                                    AppLoader.showError("ไม่สามารถเชื่อมต่อได้");
                                  }
                                },
                              ),
                            ),
                          ),
                          SizedBox(
                            height: mediaQuery(context, 'h', 50),
                          ),
                          ClipOval(
                            child: Material(
                              color: Colors.transparent, // button color
                              child: InkWell(
                                splashColor: AppColors.color, // inkwell color
                                child: SizedBox(
                                  width: mediaQuery(context, 'w', 90),
                                  height: mediaQuery(context, 'h', 90),
                                  child: Icon(
                                    FontAwesomeIcons.trashAlt,
                                    color: AppColors.color_gold,
                                    size: 21,
                                  ),
                                ),
                                onTap: () async {
                                  alertConfirm(
                                      context,
                                      "ยืนยันการลบข้อมูล",
                                      "",
                                      TodoList.data[i].todolistID,
                                      TodoList.data[i].employeeID);
                                },
                              ),
                            ),
                          )
                        ],
                      ),
                    )
                  : SizedBox(
                      width: mediaQuery(context, 'w', 90),
                      height: mediaQuery(context, 'h', 90),
                    ),
            ],
          ),
        ),
      );
      list.add(Container(
        height: 1,
      ));
      num = num + 1;
    }
    return list;
  }

  _noData(context, String text) {
    return Container(
      width: mediaQuery(context, 'w', 1005),
      padding: EdgeInsets.all(
        mediaQuery(context, 'h', 50),
      ),
      margin: EdgeInsets.only(
        bottom: mediaQuery(context, 'h', 40),
      ),
      decoration: BoxDecoration(
        borderRadius: new BorderRadius.all(
          Radius.circular(
            mediaQuery(context, 'h', 20),
          ),
        ),
        boxShadow: [
          appShadow(),
        ],
        color: Colors.white,
      ),
      child:
          Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
        Text(
          'ไม่มีข้อมูล' + text,
          style: TextStyle(
            fontSize: 20,
            color: Colors.red,
          ),
        )
      ]),
    );
  }

  _buildButton(context, text, bgColor, fontColor, onActive) {
    return ButtonTheme(
      minWidth: mediaQuery(context, "w", 477),
      height: mediaQuery(context, "h", 120),
      child: FlatButton(
        shape: new RoundedRectangleBorder(
            borderRadius: new BorderRadius.circular(
              mediaQuery(context, "w", 50),
            ),
            side: BorderSide(color: AppColors.color)),
        color: onActive ? Colors.deepPurple[400] : bgColor,
        textColor: Colors.red,
        padding: EdgeInsets.all(
          mediaQuery(context, "w", 10),
        ),
        onPressed: () {
          if (text == "ทั้งหมด") {
            setState(() {
              setText = text;
            });
            loadData();
          } else if (text == "สัปดาห์นี้") {
            setState(() {
              setText = text;
              loadWeekData();
            });
          } else if (text == "เดือนนี้") {
            setState(() {
              setText = text;
            });
            loadWeekMonthData();
          } else {
            Navigator.of(context).pop(false);
          }
          print(text);
        },
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14.0,
            color: fontColor,
          ),
        ),
      ),
    );
  }

  alertConfirm(context, title, message, String todoListID, String employeeID) {
    return showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return Center(
          child: AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(
                Radius.circular(
                  mediaQuery(context, 'h', 50),
                ),
              ),
            ),
            title: Column(
              children: <Widget>[
                Container(
                  child: Icon(
                    FontAwesomeIcons.exclamationCircle,
                    size: mediaQuery(context, 'h', 240),
                    color: AppColors.color,
                  ),
                ),
              ],
            ),
            content: Container(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Text(
                    title,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: mediaQuery(context, 'h', 60),
                    ),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 10),
                  ),
                  Text(
                    message,
                    style: TextStyle(
                      fontSize: mediaQuery(context, 'h', 46),
                    ),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 40),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      ButtonTheme(
                        minWidth: mediaQuery(context, 'h', 320),
                        height: mediaQuery(context, 'h', 120),
                        child: RaisedButton(
                          color: Colors.white,
                          shape: new RoundedRectangleBorder(
                            borderRadius: new BorderRadius.circular(
                              mediaQuery(context, 'h', 50),
                            ),
                            side: BorderSide(
                              color: AppColors.color.withOpacity(0.51),
                            ),
                          ),
                          onPressed: () {
                            TodoList.deleteData(
                                context, todoListID, employeeID);
                          },
                          splashColor: AppColors.color,
                          child: Text(
                            'ตกลง',
                            style: TextStyle(
                              color: AppColors.color,
                              fontSize: mediaQuery(context, 'h', 46),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(
                        width: mediaQuery(context, 'w', 20),
                      ),
                      ButtonTheme(
                        minWidth: mediaQuery(context, 'h', 320),
                        height: mediaQuery(context, 'h', 120),
                        child: RaisedButton(
                          color: Colors.white,
                          shape: new RoundedRectangleBorder(
                            borderRadius: new BorderRadius.circular(
                              mediaQuery(context, 'h', 50),
                            ),
                            side: BorderSide(
                              color: AppColors.color.withOpacity(0.51),
                            ),
                          ),
                          onPressed: () {
                            Navigator.of(context).pop(false);
                          },
                          splashColor: AppColors.color,
                          child: Text(
                            "ยกเลิก",
                            style: TextStyle(
                              color: AppColors.color,
                              fontSize: mediaQuery(context, 'h', 46),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
} //class
