import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:peasmartcare/blocs/coordinator_list/coordinator_list_bloc.dart';
import 'package:peasmartcare/blocs/coordinator_save/coordinator_save_bloc.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/models/coordinator_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/utils/app_util.dart';
import 'package:peasmartcare/widgets/empty_box.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';

class CoordinatorForm extends StatefulWidget {
  final CoordinatorModel coordinator;

  const CoordinatorForm({
    Key key,
    this.coordinator,
  }) : super(key: key);
  @override
  _CoordinatorFormState createState() => _CoordinatorFormState();
}

class _CoordinatorFormState extends State<CoordinatorForm> {
  final _formKey = GlobalKey<FormState>();
  TextEditingController _fullname = TextEditingController();
  TextEditingController _position = TextEditingController();
  TextEditingController _phone = TextEditingController();
  TextEditingController _idCard = TextEditingController();
  TextEditingController _otherContact = TextEditingController();
  // String _positionValue;
  // String _positionName;
  bool _isValidate = true;
  bool _isCreate = true;

  @override
  void initState() {
    setState(() => _isCreate = widget.coordinator.id == null);

    context.read<CoordinatorSaveBloc>().add(
          CoordinatorSaveGetData(coordinator: widget.coordinator),
        );

    super.initState();
  }

  @override
  void dispose() {
    _fullname.dispose();
    _phone.dispose();
    _idCard.dispose();
    _otherContact.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        _form(),
      ],
    );
  }

  Widget _form() {
    TextStyle textStyle = TextStyle(color: Color(AppData.primaryColor), fontSize: 18);
    TextStyle errortyle = TextStyle(color: Colors.orange[900], fontSize: 18, height: 0.6);
    return BlocListener<CoordinatorSaveBloc, CoordinatorSaveState>(
      listener: (context, state) {
        if (state is CoordinatorSaveLoaded) {
          if (state.saveSuccess != null && state.saveSuccess) {
            SweetAlert.show(
              context,
              subtitle: "บันทึกข้อมูลสำเร็จ",
              style: SweetAlertStyle.success,
              showCancelButton: false,
              onPress: (bool isConfirm) {
                if (isConfirm) {
                  context.read<CoordinatorListBloc>().add(CoordinatorListGetList());
                  Navigator.pop(context);
                  Navigator.pop(context);
                  return false;
                }
              },
            );

            // Navigator
          } else if (state.saveSuccess != null && !state.saveSuccess) {
            SweetAlert.show(
              context,
              subtitle: state.errorMessage,
              style: SweetAlertStyle.error,
            );
          } else if (state.saveSuccess == null) {
            CoordinatorModel coordinator = state.result;
            // CoordinatorPositionModel position = coordinator.position != null ? _positionList.singleWhere((item) => item.name == coordinator.position) : null;
            _fullname.text = coordinator.fullname;
            _position.text = coordinator.position;
            _phone.text = coordinator.phone;
            _otherContact.text = coordinator.otherContact;
            _idCard.text = coordinator.idCard;
          }
        } else if (state is CoordinatorSaveErrorUnauthorized) {
          Navigator.of(context).popUntil((route) => route.isFirst);
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => LogoutPage()),
          );
        }
      },
      child: BlocBuilder<CoordinatorSaveBloc, CoordinatorSaveState>(
        builder: (context, state) {
          if (state is CoordinatorSaveLoading) {
            return Loading();
          } else if (state is CoordinatorSaveLoaded) {
            return Form(
              key: _formKey,
              child: Center(
                child: Container(
                  constraints: BoxConstraints(maxWidth: 500),
                  child: Column(
                    children: <Widget>[
                      SizedBox(
                        height: 40,
                      ),
                      Container(
                        height: 85,
                        padding: EdgeInsets.only(left: 30, right: 30),
                        child: TextFormField(
                          validator: (value) {
                            if (value.isEmpty) {
                              return "กรุณากรอกชื่อผู้ติดต่อ";
                            }
                            return null;
                          },
                          // initialValue: coordinator.name != null ? coordinator.name.split(' ')[0]:"",
                          controller: _fullname,
                          maxLines: 1,
                          style: textStyle,
                          decoration: InputDecoration(
                            hintText: "ชื่อผู้ติดต่อ",
                            hintStyle: textStyle,
                            labelText: "ชื่อผู้ติดต่อ",
                            labelStyle: textStyle,
                            errorStyle: errortyle,
                            floatingLabelBehavior: FloatingLabelBehavior.auto,
                            filled: true,
                            fillColor: Color(AppData.whiteColor),
                            contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                            border: OutlineInputBorder(
                              borderRadius: const BorderRadius.all(
                                const Radius.circular(30),
                              ),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        height: 85,
                        padding: EdgeInsets.only(left: 30, right: 30),
                        child: TextFormField(
                          // validator: (value) {
                          //   if (value.isEmpty) {
                          //     return "กรุณากรอกตำแหน่ง";
                          //   }
                          //   return null;
                          // },
                          controller: _position,
                          maxLines: 1,
                          style: textStyle,
                          decoration: InputDecoration(
                            hintText: "ตำแหน่ง",
                            hintStyle: textStyle,
                            labelText: "ตำแหน่ง",
                            labelStyle: textStyle,
                            errorStyle: errortyle,
                            floatingLabelBehavior: FloatingLabelBehavior.auto,
                            filled: true,
                            fillColor: Color(AppData.whiteColor),
                            contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                            border: OutlineInputBorder(
                              borderRadius: const BorderRadius.all(
                                const Radius.circular(30),
                              ),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        height: 85,
                        padding: EdgeInsets.only(left: 30, right: 30),
                        child: TextFormField(
                          validator: (value) {
                            if (value.isEmpty) {
                              return "กรุณากรอกหมายเลขโทรศัพท์";
                            } else if (value.isNotEmpty && !AppUtil.isPhoneNumber(value)) {
                              return "หมายเลขโทรศัพท์ไม่ถูกต้อง";
                            }
                            return null;
                          },
                          controller: _phone,
                          maxLines: 1,
                          style: textStyle,
                          keyboardType: TextInputType.number,
                          decoration: InputDecoration(
                            hintText: "หมายเลขโทรศัพท์",
                            hintStyle: textStyle,
                            labelText: "หมายเลขโทรศัพท์",
                            labelStyle: textStyle,
                            errorStyle: errortyle,
                            floatingLabelBehavior: FloatingLabelBehavior.auto,
                            filled: true,
                            fillColor: Color(AppData.whiteColor),
                            contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                            border: OutlineInputBorder(
                              borderRadius: const BorderRadius.all(
                                const Radius.circular(30),
                              ),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        height: 85,
                        padding: EdgeInsets.only(left: 30, right: 30),
                        child: TextFormField(
                          validator: (value) {
                            if (value.isEmpty) {
                              return "กรุณากรอกบัตรประชาชน";
                            } else if (value.isNotEmpty && !AppUtil.isIDCard(value)) {
                              return "บัตรประชาชนไม่ถูกต้อง";
                            }
                            return null;
                          },
                          controller: _idCard,
                          maxLines: 1,
                          style: textStyle,
                          keyboardType: TextInputType.number,
                          decoration: InputDecoration(
                            hintText: "บัตรประชาชน",
                            hintStyle: textStyle,
                            labelText: "บัตรประชาชน",
                            labelStyle: textStyle,
                            errorStyle: errortyle,
                            floatingLabelBehavior: FloatingLabelBehavior.auto,
                            filled: true,
                            fillColor: Color(AppData.whiteColor),
                            contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                            border: OutlineInputBorder(
                              borderRadius: const BorderRadius.all(
                                const Radius.circular(30),
                              ),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        height: 85,
                        padding: EdgeInsets.only(left: 30, right: 30),
                        child: TextFormField(
                          validator: (value) {
                            // if (value.isEmpty) {
                            //   return "กรุณากรอกนามสกุล";
                            // }
                            return null;
                          },
                          controller: _otherContact,
                          maxLines: 3,
                          style: textStyle,
                          decoration: InputDecoration(
                            hintText: "ช่องทางติดต่ออื่น ๆ",
                            hintStyle: textStyle,
                            labelText: "ช่องทางติดต่ออื่น ๆ",
                            labelStyle: textStyle,
                            errorStyle: errortyle,
                            floatingLabelBehavior: FloatingLabelBehavior.auto,
                            filled: true,
                            fillColor: Color(AppData.whiteColor),
                            contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                            border: OutlineInputBorder(
                              borderRadius: const BorderRadius.all(
                                const Radius.circular(30),
                              ),
                            ),
                          ),
                        ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 30, 0, 15),
                            child: RaisedButton(
                              padding: EdgeInsets.only(top: 12, left: 30, right: 30, bottom: 12),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(7),
                              ),
                              child: Text(
                                "บันทึก",
                                style: TextStyle(
                                  fontWeight: FontWeight.w800,
                                  color: Colors.white,
                                  fontSize: 18,
                                ),
                              ),
                              color: Color(AppData.yellowColor),
                              onPressed: () {
                                setState(() {
                                  _isValidate = _formKey.currentState.validate();
                                });

                                if (_isValidate) {
                                  context.read<CoordinatorSaveBloc>().add(
                                        CoordinatorSaveOnSubmit(
                                          id: widget.coordinator.id,
                                          fullname: _fullname.text,
                                          position: _position.text,
                                          phone: _phone.text,
                                          idCard: _idCard.text,
                                          otherContact: _otherContact.text,
                                          isCreate: _isCreate,
                                        ),
                                      );
                                }
                              },
                            ),
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 30, 0, 15),
                            child: RaisedButton(
                              padding: EdgeInsets.only(top: 12, left: 30, right: 30, bottom: 12),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(7),
                              ),
                              child: Text(
                                "ยกเลิก",
                                style: TextStyle(
                                  fontWeight: FontWeight.w800,
                                  color: Colors.white,
                                  fontSize: 18,
                                ),
                              ),
                              color: Color(AppData.greyColor),
                              onPressed: () {
                                Navigator.pop(context);
                              },
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            );
          }

          return EmptyBox();
        },
      ),
    );
  }
}
