import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.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/style.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/model/customer_contact.dart';
import 'package:mwf_app/set5/customer_representative_list.dart';
import 'package:nextflow_thai_personal_id/nextflow_thai_personal_id.dart';

class CustomerRepresentativeEdit extends StatefulWidget {
  final index;

  CustomerRepresentativeEdit(this.index);

  @override
  _CustomerRepresentativeEditState createState() =>
      _CustomerRepresentativeEditState(this.index);
}

class _CustomerRepresentativeEditState
    extends State<CustomerRepresentativeEdit> {
  var index;

  _CustomerRepresentativeEditState(this.index);
  bool isLoading = false;
  bool isIdCardValid = true;
  TextEditingController name = TextEditingController(); // ชื่อผู้ติดต่อ
  TextEditingController lastName = TextEditingController(); // นามสกุล
  TextEditingController position = TextEditingController(); // ตำแหน่ง
  TextEditingController phone = TextEditingController(); // เบอร์โทรศัพท์
  TextEditingController personCardId = TextEditingController(); // เบอร์โทรศัพท์
  TextEditingController contact =
      TextEditingController(); // ช่องทางการติดต่ออื่น ๆ
  String customerContactID;
  ThaiIdValidator validator = ThaiIdValidator();

  @override
  void initState() {
    super.initState();
    setState(() {
      isLoading = true;
      name.text = CustomerContact.data[index].firstName;
      lastName.text = CustomerContact.data[index].lastName;
      position.text = CustomerContact.data[index].position;
      phone.text = CustomerContact.data[index].contactTel;
      contact.text = CustomerContact.data[index].contactEtc;
      customerContactID = CustomerContact.data[index].customerContactInfoId;
      personCardId.text =
          CustomerContact.data[index].citizenNumber.toString() != "null"
              ? CustomerContact.data[index].citizenNumber.toString()
              : "";
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;
    double _height = MediaQuery.of(context).size.height;
    Header.routes = CustomerRepresentativeList();
    return GestureDetector(
      onTap: (){
        FocusScope.of(context).unfocus();
      },
      child: 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', 950),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      "รายชื่อผู้แทนลูกค้า",
                      style: AppStyle.headTextStyle(context),
                    )
                  ],
                ),
              ),
              Container(
//            color: Colors.red,
                width: _width,
                height: mediaQuery(context, 'h', 1150),
                margin: EdgeInsets.only(
                  top: mediaQuery(context, 'h', 1050),
                  left: mediaQuery(context, 'w', 60),
                  right: mediaQuery(context, 'w', 60),
                ),
                child: SingleChildScrollView(
                  padding: EdgeInsets.only(
                    bottom: _height / 3.5),
                  child: Column(
                    children: <Widget>[
                      _buildTextMenu(context, "ชื่อผู้ติดต่อ"),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          _buildRow(context, name),
                        ],
                      ),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "นามสกุล"),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          _buildRow(context, lastName),
                        ],
                      ),
                      _buildSizeBox(context),
                      _buildTextMenuNotRequred(context, "ตำแหน่ง"),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          _buildRow(context, position),
                        ],
                      ),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "หมายเลขโทรศัพท์"),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          _buildRowTelNumber(context, phone),
                        ],
                      ),
                      _buildSizeBox(context),
                      _buildTextMenuNotRequred(context, "ช่องทางติดต่ออื่นๆ"),
                      _buildSizeBox(context),
                      _buildTextArea(context),
                      _buildSizeBox(context),
                      _buildTextMenuNotRequred(context, "หมายเลขบัตรประชาชน"),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          _buildRowIdCard(context, personCardId),
                        ],
                      ),
                      _buildSizeBox(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),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

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

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

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

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

  _buildRowTelNumber(context, TextEditingController controller) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: new TextField(
        keyboardType: TextInputType.number,
        controller: controller,
        enabled: true,
        decoration: new InputDecoration(
            border: new 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: new TextStyle(color: Colors.grey[800]),
            fillColor: Colors.white70),
      ),
    );
  }

  _buildRowIdCard(context, TextEditingController controller) {
    isZero() {
      if (controller.text.length > 0 && isIdCardValid == false) {
        return mediaQuery(context, 'h', 196);
      } else if (controller.text.length == 0 && isIdCardValid == false) {
        setState(() {
          isIdCardValid = true;
        });
        return mediaQuery(context, 'h', 110);
      } else {
        return mediaQuery(context, 'h', 110);
      }
    }

    return Container(
      height: isZero(),
      width: mediaQuery(context, 'w', 1005),
      child: new TextField(
        keyboardType: TextInputType.number,
        controller: controller,
        onChanged: (value) {
          var res = validator.validate(value);
          if (res != null) {
            isIdCardValid = false;
          } else {
            isIdCardValid = true;
          }
        },
        enabled: true,
        maxLength: 13,
        decoration: new InputDecoration(
            errorText:
                isIdCardValid ? null : "กรุณาตรวจสอบ เลขบัตรประจำตัว อีกครั้ง",
            border: new 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: new TextStyle(color: Colors.grey[800]),
            fillColor: Colors.white70),
      ),
    );
  }

  _buildRow(context, TextEditingController controller) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: new TextField(
        controller: controller,
        enabled: true,
        decoration: new InputDecoration(
            border: new 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: new TextStyle(color: Colors.grey[800]),
            fillColor: Colors.white70),
      ),
    );
  }

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

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

  save(context) async {
    if (await checkForm([
      name.text,
      lastName.text,
      phone.text,
    ])) {
      setState(() {
        isLoading = true;
      });
      Map<String, dynamic> data = {
        "customerContactInfoId": customerContactID.toString(),
        "firstName": name.text.toString(),
        "lastName": lastName.text.toString(),
        "Position": position.text.toString(),
        "ContactTel": phone.text.toString(),
        "ContactEtc": contact.text.toString(),
        "citizenNumber": personCardId.text.toString(),
        "authenKey": AppUrl.AuthenKey.toString()
      };
      print(data);
      await new Future.delayed(const Duration(milliseconds: 2000));
      CustomerContact.updateData(context, data);
      setState(() {
        isLoading = false;
      });
    } else {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }
} //class
