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/header.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/convert.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/model/customer_care.dart';
import 'package:buddhist_datetime_dateformat/buddhist_datetime_dateformat.dart';
import 'package:mwf_app/set3/customer_staff_list.dart';

class EditStaff extends StatefulWidget {
  final name;
  final String startDate;
  final String endDate;
  final customerCareID;

  EditStaff(
    this.name,
    this.startDate,
    this.endDate,
    this.customerCareID,
  );

  @override
  _EditStaffState createState() => _EditStaffState(
        this.name,
        this.startDate,
        this.endDate,
        this.customerCareID,
      );
}

class _EditStaffState extends State<EditStaff> {
  bool acceptCondition = false;
  bool isLoading = false;
  final name;
  final startDate;
  final endDate;
  final customerCareID;

  _EditStaffState(this.name, this.startDate, this.endDate, this.customerCareID);

  TextEditingController customerCareName = TextEditingController();
  TextEditingController startDateController = TextEditingController();
  TextEditingController endDateController = TextEditingController();
  String strStartDate = "";
  String strEndDate = "";
  @override
  void initState() {
    super.initState();
    Header.routes = Customerstaff_list();
    Intl.defaultLocale = 'th';
    initializeDateFormatting();
    customerCareName.text = name;
    if (startDate.toString().isNotEmpty && endDate.toString().isNotEmpty) {
      strStartDate = startDate;
      strEndDate = AppConvert.dateOnly(endDate)!= "" ? endDate : "";
      startDateController.text =
          AppConvert.date(startDate.toString().split("T")[0]).toString();

      if(strEndDate.isNotEmpty){
        endDateController.text =
            AppConvert.date(endDate.toString().split("T")[0]).toString();
        print(endDate);
        print(endDateController.text);
      }
    }else if(endDate.toString().isEmpty){
      strStartDate = startDate;
      strEndDate = "";
      startDateController.text =
          AppConvert.date(startDate.toString().split("T")[0]).toString();
      endDateController.clear();
    }
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;
    return Material(
      color: AppColors.bgColor,
      child:  WillPopScope(
        onWillPop: () async {
          Get.offAll(Header.routes);
          return false;
        },
        child: Stack(
          children: <Widget>[
            Header.headerListPage(context),
            Header.mainMenu(context),
            Container(
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 990),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    AppStrings.service_Modify_delete_Staff,
                    style: TextStyle(
                        fontSize: mediaQuery(context, 'h', 60),
                        color: AppColors.color_gold),
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
            Container(
              width: _width,
              height: mediaQuery(context, 'h', 1200),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 1150),
                left: mediaQuery(context, 'w', 60),
                right: mediaQuery(context, 'w', 60),
              ),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        _buildTextMenu(context, AppStrings.service_FullName),
                      ],
                    ),
                    _buildSizeBox(context),
                    Row(
                      children: <Widget>[
                        _buildRow(context),
                      ],
                    ),
                    _buildSizeBox(context),
                    _buildTextMenuTwoColumn(
                      context,
                      AppStrings.EditStaff_StartDate,
                      AppStrings.EditStaff_EndDate,
                      350.0,
                    ),
                    _buildTextFieldTwoColumn(context),
                    _buildSizeBox(context),
                    _buildSizeBox(context),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        _buildButton(
                            context, "ยกเลิก", Colors.white, AppColors.color),
                        _buildButton(
                            context, "บันทึก", AppColors.color, Colors.white),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _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),
      ],
    );
  }

  _buildTextFieldTwoColumn(context) {
    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: strStartDate != ""
                    ? DateTime.parse(strStartDate)
                    : 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(() {
                      startDateController.clear();
                      strStartDate = "";
                    });
                },
              );
              if (newDate != null) {
                var dtArray = newDate.toString().split(" ");
                setState(() {
                  var formatter = DateFormat.yMd();
                  var showDate =
                      formatter.formatInBuddhistCalendarThai(newDate);
                  startDateController.text = showDate;
                  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: 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(startDateController.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 {
              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,
                textActionButton: "ลบวันที่",
                  onTapActionButton: (){
                    setState(() {
                      endDateController.clear();
                      strEndDate = "";
                    });
                },
              );
              if (newDate != null) {
                var dtArray = newDate.toString().split(" ");
                setState(() {
                  var formatter = DateFormat.yMd();
                  var showDate =
                      formatter.formatInBuddhistCalendarThai(newDate);
                  endDateController.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(endDateController.text),
                  Icon(
                    Icons.calendar_today,
                    color: Colors.grey,
                    size: mediaQuery(
                      context,
                      'h',
                      80,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        // SizedBox(
        //   width: mediaQuery(context, 'w', 10),
        // ),
        // Column(
        //   children: [                            
        //     SizedBox(
        //       height: mediaQuery(context, 'h', 105),
        //       width: mediaQuery(context, 'w', 90),
        //       child: FloatingActionButton(
        //         onPressed: () {
        //           setState(() {
        //             endDateController.clear();
        //             strEndDate = "";
        //           });
        //         },
        //         child: Text('ลบ'),
        //         shape: RoundedRectangleBorder(),
        //       ),
        //     ),
        //   ],
        // )
      ],
    );
  }

  _buildRow(context) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        controller: customerCareName,
        enabled: true,
        decoration: InputDecoration(
          border: OutlineInputBorder(
            borderRadius: const BorderRadius.all(
              const Radius.circular(50.0),
            ),
          ),
          filled: true,
          counterText: "",
          contentPadding: EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
          hintStyle: TextStyle(color: Colors.grey[800]),
          fillColor: Colors.white,
        ),
      ),
    );
  }

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

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

  _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: () {
          print(text);

          if (text == "บันทึก") {
            save(context);
          } else {
            Get.offAll(Customerstaff_list());
          }
        },
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14.0,
            color: fontColor,
          ),
        ),
      ),
    );
  }

  save(context) async {
    bool chk = await checkForm([
      customerCareName.text,
      startDate
    ]);

    if (chk != true) {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    } else {
      setState(() {
        isLoading = true;
      });

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

      Map<String, dynamic> data = {
        "customerSaleInfoId": customerCareID,
        "CustomerID": AppStrings.customerID,
        "Employeename": customerCareName.text,
        "startDate": strStartDate,
        "endDate": strEndDate.isEmpty ? null : strEndDate,
        "authenKey": AppUrl.AuthenKey
      };
      if (acceptCondition) {
        print(data);
        await Future.delayed(const Duration(milliseconds: 1000));
        await CustomerCare.updateData(context, data);
      }
      setState(() {
        isLoading = false;
      });
    }
  }
} //class
