import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rounded_date_picker/rounded_picker.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/convert.dart';
import 'package:mwf_app/service/fontsize.dart';
import 'package:mwf_app/service/header.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';

class TaskList extends StatefulWidget {
  @override
  _TaskListState createState() => _TaskListState();
}

class _TaskListState extends State<TaskList> {
  TextEditingController startDataText =
      TextEditingController(); //วันที่เริ่มต้น
  TextEditingController endDataText = TextEditingController(); //เวลาที่เริ่มต้น
  TextEditingController startTimeText = TextEditingController(); //วันที่สิ้นสุด
  TextEditingController endTimeText = TextEditingController(); //เวลาที่สิ้นสุด
  TextEditingController detailText = TextEditingController(); //รายละเอียด
  String strStartDate = "";
  String strEndDate = "";
  var startDates;
  @override
  void initState() {
    super.initState();
    print("On add taskList");
    Intl.defaultLocale = 'th';
    initializeDateFormatting();
  }

  @override
  Widget build(BuildContext context) {
    double _width = MediaQuery.of(context).size.width;

    return Material(
      color: AppColors.bgColor,
      child: Stack(
        children: <Widget>[
          Header.header2(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),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  saveTaskList(context) async {
    if (await checkForm(
        [startDataText.text, startTimeText.text, detailText.text])) {
      Map<String, dynamic> data = {
        "EmployeeID": AppUrl.EmpID.toString(),
        "saleinfoid": AppUrl.EmpID.toString(),
        "startdate": strStartDate + " " + startTimeText.text,
        "enddate": strEndDate + " " + endTimeText.text,
        "detail": detailText.text,
        "AuthenKey": AppUrl.AuthenKey
      };

      var startDate = DateTime.parse(strStartDate);

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

  saveTaskListNoRequireField(context) async {
    if (await checkForm([startDataText.text, detailText.text])) {
      if (endTimeText.text.isEmpty) {
        Map<String, dynamic> data = {
          "EmployeeID": AppUrl.EmpID.toString(),
          "saleinfoid": AppUrl.EmpID.toString(),
          "startdate": strStartDate + " " + startTimeText.text,
          "enddate": strEndDate + " " + endTimeText.text,
          "detail": detailText.text,
          "AuthenKey": AppUrl.AuthenKey
        };
        TodoList.saveData(context, data);
      } else {
        saveTaskList(context);
      }
    } else {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }

  _buildTextArea(context) {
    return Container(
      color: Colors.white,
      child: TextField(
        controller: detailText,
        maxLines: 5,
        decoration: InputDecoration(
          fillColor: Colors.white70,
          border: 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: RoundedRectangleBorder(
            borderRadius: 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 == "บันทึก") {
            // saveTaskList(context);
            saveTaskListNoRequireField(context);
          } else {
            Navigator.of(context).pop(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.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,
                textActionButton: "ลบวันที่และเวลา",
                  onTapActionButton: (){
                    setState(() {
                      startDataText.clear();
                      startTimeText.clear();
                      strStartDate = "";
                    });
                },
              );
              if (newDate != null) {
                var dtArray = newDate.toString().split(" ");
                setState(() {
                  var formatter = DateFormat.yMd();
                  var showDate =
                      formatter.formatInBuddhistCalendarThai(newDate);
                  startDataText.text = showDate;
                  strStartDate = dtArray[0];
                  print("Start Date Bud : " + startDataText.text);
                  print("Start Date : " + strStartDate.toString());
                });
              }
            },
            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: 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 != "" ?
                  startTimeText.text :
                 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(() {
                  //time.text = "time";
                  startTimeText.text = time;
                  print("Start Time : " + startTimeText.text);
                });
              }
            },
            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: 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,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  _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: 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,
                textActionButton: "ลบวันที่และเวลา",
                  onTapActionButton: (){
                    setState(() {
                      endDataText.clear();
                      endTimeText.clear();
                      strEndDate = "";
                    });
                },
              );
              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: 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: 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(() {
                  endTimeText.text = time;
                  print("end time:: " + endTimeText.text);
                });
              }
            },
            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: 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
