import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rounded_date_picker/rounded_picker.dart';
import 'package:get/get.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/fontsize.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/convert.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/model/TodoList_model.dart';
import 'package:buddhist_datetime_dateformat/buddhist_datetime_dateformat.dart';
import 'package:mwf_app/set1/schedule.dart';

class TaskListEdit extends StatefulWidget {
  String id = "TodoEdit";
  final todoNumber;

  TaskListEdit(this.todoNumber);

  @override
  _TaskListEditState createState() => _TaskListEditState(this.todoNumber);
}

class _TaskListEditState extends State<TaskListEdit> {
  final todoNumber;
  static var saveTodoNumber;
  var getTodo;
  String strStartDate = "";
  String strEndDate = "";
  String timeEndDate = "";
  String timeStartDate = "";
  String detail = "";
  _TaskListEditState(this.todoNumber);

  TextEditingController startDataText = TextEditingController();
  TextEditingController endDataText = TextEditingController();
  TextEditingController startTimeText = TextEditingController();
  TextEditingController endTimeText = TextEditingController();
  TextEditingController detailText = TextEditingController();
  var todoListID;

  var todoData;

  @override
  void initState() {
    super.initState();
    if (todoNumber != null) {
      saveTodoNumber = todoNumber;
      getTodo = saveTodoNumber;
    } else {
      getTodo = saveTodoNumber;
    }
    print("Save : " + saveTodoNumber);
    print("storage : " + getTodo);
    print("On TaskList Page");
    Intl.defaultLocale = 'th';
    initializeDateFormatting();
    loadData(); // ดึงข้อมูล
  }

  loadData() async {
    try {
      if (getTodo.toString().isNotEmpty) {
        final list = await TodoList.getReadTodoId(
            getTodo); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
        setState(() {
          DateTime strStart;
          DateTime strEnd;

          var formatter = DateFormat.yMd();
          todoData = list[0];
          todoListID = todoData['TodolistID'];
          print(list);
          startTimeText.text =
              todoData['startdate'].split('T')[1].substring(0, 5).toString();

          strStart = DateTime.parse(todoData['startdate'].split('T')[0]);

          startDataText.text = formatter.formatInBuddhistCalendarThai(strStart);

          print("Here start date :: " + startDataText.text);
          print("Here start time :: " + startTimeText.text);
          print("End time :: " +
              todoData['enddate'].split('T')[1].substring(0, 5).toString());
          strStartDate = todoData['startdate'].split('T')[0];
          timeStartDate = startTimeText.text;
          detailText.text = todoData['detail'];
          endTimeText.text = "";
          timeEndDate = "";
          endDataText.text = "";
          strEndDate = "";
          //_buildTextFieldTwoColumnStart(context, startDataText, startTimeText);
          if (todoData['enddate'] == '0001-01-01T00:00:00') {
            endTimeText.text = "";
            timeEndDate = "";
            endDataText.text = "";
            detailText.text = todoData['detail'];
          } else {
            endTimeText.text =
                todoData['enddate'].split('T')[1].substring(0, 5).toString();
            print("Here end time :: " + endTimeText.text);
            timeEndDate = endTimeText.text;
            strEnd = DateTime.parse(todoData['enddate'].split('T')[0]);
            endDataText.text = formatter.formatInBuddhistCalendarThai(strEnd);
            print("Here end endData :: " + endDataText.text);
            strEndDate = todoData['enddate'].split('T')[0];
            //_buildTextFieldTwoColumnEnd(context, endDataText, endTimeText);
          }
        });
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    Header.routes = Schedule();
    double _width = MediaQuery.of(context).size.width;
    double _height = MediaQuery.of(context).size.height;

    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),
            Container(
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 400),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(
                      top: mediaQuery(context, 'h', 0),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          AppStrings.TaskList_TaskList,
                          style: TextStyle(
                            fontSize:
                                mediaQuery(context, 'h', AppFontSize.headText),
                            color: AppColors.color_gold,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ],
                    ),
                  ),
//                    end
                ],
              ),
            ),
            Container(
//            color: Colors.red,
              width: _width,
              height: mediaQuery(context, 'h', 1700),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 500),
                left: mediaQuery(context, 'w', 60),
                right: mediaQuery(context, 'w', 60),
              ),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    _buildTextMenuTwoColumn(
                        context,
                        AppStrings.TaskList_StartDate,
                        AppStrings.TaskList_time,
                        400.0),
                    _buildSizeBox(context),
                    _buildTextFieldTwoColumnStart(
                        context, startDataText, startTimeText),
                    _buildSizeBox(context),
                    _buildTextMenuTwoColumn(context, AppStrings.TaskList_EndDate,
                        AppStrings.TaskList_time, 400.0),
                    _buildSizeBox(context),
                    _buildTextFieldTwoColumnEnd(
                        context, endDataText, endTimeText),
                    _buildSizeBox(context),
                    _buildTextMenu(context, AppStrings.TaskList_Details),
                    _buildSizeBox(context),
                    _buildSizeBox(context),
                    _buildTextArea(context),
                    _buildSizeBox(context),
                    _buildSizeBox(context),
                    _buildSizeBox(context),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        _buildButton(
                            context, "ยกเลิก", Colors.white, AppColors.color),
                        _buildButton(
                            context, "บันทึก", AppColors.color, Colors.white),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  updateTaskListNoEndTime(context) async {
    if (await checkForm([startDataText.text, detailText.text])) {
      if (endTimeText.text.isEmpty) {
        var response = await TodoList.updateData(
          context,
          todoListID,
          AppUrl.EmployeeID,
          AppUrl.EmployeeID,
          strStartDate + " " + startTimeText.text,
          strEndDate + " " + endTimeText.text,
          detailText.text,
        );
        print(response);
      } else {
        updateTaskList(context);
      }
    } else {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }

  updateTaskList(context) async {
    if (await checkForm(
        [startDataText.text, startTimeText.text, detailText.text])) {
      bool acceptCondition = false;
      var startDate = DateTime.parse(strStartDate);

      if (strEndDate.isNotEmpty && endTimeText.text.isNotEmpty) {
        var endDate = DateTime.parse(strEndDate);
        if (startDate.isBefore(endDate)) {
          acceptCondition = true;
        } else if ((startDate == endDate || startDate.isBefore(endDate)) &&
            CheckTime.checkTime(startTimeText, endTimeText)) {
          acceptCondition = true;
        } else {
          alertForm(context, "แจ้งเตือน",
              "กรุณาตรวจสอบ วันหรือเวลา เริ่มต้น และสิ้นสุดอีกครั้ง");
        }
      } else if (strEndDate.isNotEmpty && endTimeText.text.isEmpty) {
        var endDate = DateTime.parse(strEndDate);
        if (startDate == endDate || startDate.isBefore(endDate)) {
          acceptCondition = true;
        } else {
          alertForm(context, "แจ้งเตือน",
              "กรุณาตรวจสอบ วันที่เริ่มต้น และสิ้นสุดอีกครั้ง");
        }
      } else if (strEndDate.isEmpty && endTimeText.text.isNotEmpty) {
        if (CheckTime.checkTime(startTimeText, endTimeText)) {
          acceptCondition = true;
        } else {
          alertForm(context, "แจ้งเตือน",
              "กรุณาตรวจสอบ เวลา เริ่มต้น และสิ้นสุดอีกครั้ง");
        }
      } else {
        acceptCondition = true;
      }

      if (acceptCondition) {
        var response = await TodoList.updateData(
          context,
          todoListID,
          AppUrl.EmployeeID,
          AppUrl.EmployeeID,
          strStartDate + " " + startTimeText.text,
          strEndDate + " " + endTimeText.text,
          detailText.text,
        );
        print(response);
      }
    } else {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }

  _buildTextArea(context) {
    return Container(
      color: Colors.white,
      child: TextField(
        controller: detailText,
        maxLines: 5,
        decoration: InputDecoration(
            fillColor: Colors.white70,
            border: new OutlineInputBorder(
              borderRadius: const BorderRadius.all(
                const Radius.circular(10.0),
              ),
            ),
            hintText: "",
            labelText: ''),
      ),
    );
  }

  _buildTextMenuTwoColumn(context, text_1, text_2, width) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        _buildTextMenu(context, text_1),
        SizedBox(
          width: mediaQuery(context, "w", width),
        ),
        _buildTextMenu(context, text_2),
      ],
    );
  }

  _buildTextMenu(context, text) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Text(
          text + " :",
          style: TextStyle(
              fontSize: mediaQuery(context, 'h', AppFontSize.label),
              color: AppColors.Black),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  _buildSizeBox(context) {
    return SizedBox(
      height: mediaQuery(context, "h", 15),
    );
  }

  _buildButton(context, text, bgColor, fontColor) {
    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: bgColor,
        textColor: Colors.red,
        padding: EdgeInsets.all(
          mediaQuery(context, "w", 10),
        ),
        onPressed: () {
          if (text == "บันทึก") {
            updateTaskListNoEndTime(context);
          } else { 
            Get.offAll(Header.routes);
            return false;
          }
          print(text);
        },
        child: Text(
          text,
          style: TextStyle(
            fontSize: mediaQuery(context, "h", AppFontSize.btn),
            color: fontColor,
          ),
        ),
      ),
    );
  }

  _buildTextFieldTwoColumnStart(context, TextEditingController startDataText,
      TextEditingController time) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          child: GestureDetector(
            onTap: () async {
              DateTime newDate = await showRoundedDatePicker(
                context: context,
                initialDate: DateTime.parse(strStartDate),
                firstDate: DateTime(DateTime.now().year - 10),
                lastDate: DateTime(DateTime.now().year + 10),
                locale: Locale('th', 'TH'),
                era: EraMode.BUDDHIST_YEAR,
                theme: ThemeData(primarySwatch: Colors.deepPurple),
                height: 280,
              );
              if (newDate != null) {
                print(newDate);
                var dtArray = newDate.toString().split(" ");
                setState(() {
                  var formatter = DateFormat.yMd();
                  var showDate =
                      formatter.formatInBuddhistCalendarThai(newDate);
                  startDataText.text = showDate;
                  print("Showdatetext :: " + showDate);
                  print("Showdatetext :: " + startDataText.toString());
                  strStartDate = dtArray[0];
                });
              }
            },
            child: Container(
              height: mediaQuery(context, 'h', 105),
              width: mediaQuery(context, 'w', 490),
              padding: EdgeInsets.only(
                left: mediaQuery(context, 'h', 20),
                right: mediaQuery(context, 'h', 20),
              ),
              decoration: BoxDecoration(
                borderRadius: new BorderRadius.all(
                  Radius.circular(
                    mediaQuery(
                      context,
                      'h',
                      150,
                    ),
                  ),
                ),
                border: Border.all(
                  color: Colors.grey[500],
                ),
                color: Colors.white,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(startDataText.text),
                  Icon(
                    Icons.calendar_today,
                    color: Colors.grey,
                    size: mediaQuery(
                      context,
                      'h',
                      80,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          child: GestureDetector(
            onTap: () async {
              TimeOfDay newTime = await showTimePicker(
                context: context,
                initialTime: startTimeText.text != ""
                    ? TimeOfDay(
                        hour: CheckTime.getHour(startTimeText),
                        minute: CheckTime.getMin(startTimeText))
                    : TimeOfDay.now(),
                builder: (context, child) {
                  return Column(children: <Widget>[
                    MediaQuery(
                        data: MediaQuery.of(context)
                            .copyWith(alwaysUse24HourFormat: true),
                        child: child),
                    Theme(
                      data: Theme.of(context).copyWith(
                        primaryColor: AppColors.color,
                        accentColor: AppColors.color_gold,
                        colorScheme: ColorScheme.light(
                          primary: AppColors.color,
                        ),
                        buttonTheme: ButtonThemeData(
                          textTheme: ButtonTextTheme.primary,
                        ),
                      ),
                      child: Container(
                        height: 0,
                        width: 0,
                        child: child,
                      ),
                    ),
                  ]);
                },
              );
              if (newTime != null) {
                String hour = newTime.hour.toString();
                String min = newTime.minute.toString();
                var time = AppConvert.fillZeroTime(newTime, hour, min);
                setState(() {
                  startTimeText.text = time;
                  timeStartDate = time;
                  print(timeStartDate);
                });
              }
            },
            child: Container(
              height: mediaQuery(context, 'h', 105),
              width: mediaQuery(context, 'w', 490),
              padding: EdgeInsets.only(
                left: mediaQuery(context, 'h', 20),
                right: mediaQuery(context, 'h', 20),
              ),
              decoration: BoxDecoration(
                borderRadius: new BorderRadius.all(
                  Radius.circular(
                    mediaQuery(
                      context,
                      'h',
                      150,
                    ),
                  ),
                ),
                border: Border.all(
                  color: Colors.grey[500],
                ),
                color: Colors.white,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(time.text),
                  Icon(
                    Icons.access_time,
                    color: Colors.grey,
                    size: mediaQuery(
                      context,
                      'h',
                      80,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
//endfield

  _buildTextFieldTwoColumnEnd(
      context, TextEditingController endDataText, TextEditingController time) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          child: GestureDetector(
            onTap: () async {
              DateTime newDate = await showRoundedDatePicker(
                context: context,
                initialDate: strEndDate != ""
                    ? DateTime.parse(strEndDate)
                    : DateTime.now(),
                firstDate: DateTime(DateTime.now().year - 10),
                lastDate: DateTime(DateTime.now().year + 10),
                locale: Locale('th', 'TH'),
                era: EraMode.BUDDHIST_YEAR,
                theme: ThemeData(primarySwatch: Colors.deepPurple),
                height: 280,
              );
              if (newDate != null) {
                var dtArray = newDate.toString().split(" ");
                setState(() {
                  var formatter = DateFormat.yMd();
                  var showDate =
                      formatter.formatInBuddhistCalendarThai(newDate);
                  endDataText.text = showDate;
                  strEndDate = dtArray[0];
                });
              }
            },
            child: Container(
              height: mediaQuery(context, 'h', 105),
              width: mediaQuery(context, 'w', 490),
              padding: EdgeInsets.only(
                left: mediaQuery(context, 'h', 20),
                right: mediaQuery(context, 'h', 20),
              ),
              decoration: BoxDecoration(
                borderRadius: new BorderRadius.all(
                  Radius.circular(
                    mediaQuery(
                      context,
                      'h',
                      150,
                    ),
                  ),
                ),
                border: Border.all(
                  color: Colors.grey[500],
                ),
                color: Colors.white,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(endDataText.text),
                  Icon(
                    Icons.calendar_today,
                    color: Colors.grey,
                    size: mediaQuery(
                      context,
                      'h',
                      80,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          child: GestureDetector(
            onTap: () async {
              TimeOfDay newTime = await showTimePicker(
                context: context,
                initialTime: endTimeText.text != ""
                    ? TimeOfDay(
                        hour: CheckTime.getHour(endTimeText),
                        minute: CheckTime.getMin(endTimeText))
                    : TimeOfDay.now(),
                builder: (context, child) {
                  return Container(
                    child: Column(children: <Widget>[
                      MediaQuery(
                          data: MediaQuery.of(context)
                              .copyWith(alwaysUse24HourFormat: true),
                          child: child),
                      Theme(
                        data: Theme.of(context).copyWith(
                          primaryColor: AppColors.color,
                          accentColor: AppColors.color_gold,
                          colorScheme: ColorScheme.light(
                            primary: AppColors.color,
                          ),
                          buttonTheme: ButtonThemeData(
                            textTheme: ButtonTextTheme.primary,
                          ),
                        ),
                        child: Container(
                          height: 0,
                          width: 0,
                          child: child,
                        ),
                      ),
                    ]),
                  );
                },
              );
              if (newTime != null) {
                String hour = newTime.hour.toString();
                String min = newTime.minute.toString();
                var time = AppConvert.fillZeroTime(newTime, hour, min);
                setState(() {
                  endTimeText.text = time;
                  timeEndDate = time;
                  print(timeEndDate);
                });
              }
            },
            child: Container(
              height: mediaQuery(context, 'h', 105),
              width: mediaQuery(context, 'w', 490),
              padding: EdgeInsets.only(
                left: mediaQuery(context, 'h', 20),
                right: mediaQuery(context, 'h', 20),
              ),
              decoration: BoxDecoration(
                borderRadius: new BorderRadius.all(
                  Radius.circular(
                    mediaQuery(
                      context,
                      'h',
                      150,
                    ),
                  ),
                ),
                border: Border.all(
                  color: Colors.grey[500],
                ),
                color: Colors.white,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(time.text),
                  Icon(
                    Icons.access_time,
                    color: Colors.grey,
                    size: mediaQuery(
                      context,
                      'h',
                      80,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
} //class
