import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:peasmartcare/blocs/register/register_bloc.dart';
import 'package:peasmartcare/blocs/resend_otp/resend_otp_bloc.dart';
import 'package:peasmartcare/components/body_layout.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/constraints/image_asset.dart';
import 'package:peasmartcare/pages/auth/send_otp.dart';
import 'package:peasmartcare/utils/app_util.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';
import 'package:peasmartcare/pages/select_electricity_location/select_electricity_location.dart';

class RegisterPage extends StatefulWidget {
  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final _formKey = GlobalKey<FormState>();
  TextEditingController _firstname = TextEditingController();
  TextEditingController _lastname = TextEditingController();
  TextEditingController _idCard = TextEditingController();
  TextEditingController _phone = TextEditingController();
  int cardTypeSelectValue = 1;
  String cardTypeSelectName = "บัตรประชาชน";

  List cardTypeList = [
    CardType(name: "บัตรประชาชน", typeId: 1),
    CardType(name: "พาสปอร์ต", typeId: 2),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: PEAAppBar(
      //   leading: EmptyBox(heightFactor: 0),
      //   actions: <Widget>[],
      // ),
      body: BodyLayout(
        layoutType: LayoutType.ONLY_CHILD,
        color: Colors.purple[200],
        top: 50,
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                _body(),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _body() {
    return Positioned(
      child: Padding(
        padding: const EdgeInsets.only(top: 0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              alignment: Alignment.topCenter,
              child: Image.asset(
                ImageAsset.peaHorizontalLogo,
                width: 300,
                fit: BoxFit.fill,
              ),
            ),
            SizedBox(
              height: 20,
            ),
            Text("ลงทะเบียน",
                style:
                    TextStyle(fontSize: 32, color: Color(AppData.yellowColor))),
            _form()
          ],
        ),
      ),
    );
  }

  Widget _form() {
    Size deviceSize = MediaQuery.of(context).size;
    TextStyle textStyle =
        TextStyle(color: Color(AppData.primaryColor), fontSize: 18);
    TextStyle errortyle =
        TextStyle(color: Colors.orange[900], fontSize: 18, height: 0.6);
    return Form(
      key: _formKey,
      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;
              },
              controller: _firstname,
              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: _lastname,
              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),
            width: deviceSize.width,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: cardTypeList
                  .map((data) => Row(
                        children: <Widget>[
                          Radio(
                            groupValue: cardTypeSelectValue,
                            value: data.typeId,
                            onChanged: (val) {
                              setState(() {
                                cardTypeSelectValue = data.typeId;
                                cardTypeSelectName = data.name;
                              });
                            },
                          ),
                          GestureDetector(
                            onTap: () {
                              setState(() {
                                cardTypeSelectValue = data.typeId;
                                cardTypeSelectName = data.name;
                              });
                            },
                            child: Text(data.name, style: textStyle),
                          ),
                        ],
                      ))
                  .toList(),
            ),
          ),
          Container(
            height: 85,
            padding: EdgeInsets.only(left: 30, right: 30),
            child: TextFormField(
              validator: (value) {
                if (value.isEmpty) {
                  return "กรุณากรอก$cardTypeSelectName";
                } else if (cardTypeSelectValue == 1 &&
                    !AppUtil.isIDCard(value)) {
                  return "บัตรประชาชนไม่ถูกต้อง";
                  // return null;
                } else if (cardTypeSelectValue == 2 &&
                    !AppUtil.isPassport(value)) {
                  return "พาสปอร์ตไม่ถูกต้อง";
                  // return null;
                }
                return null;
              },
              controller: _idCard,
              maxLines: 1,
              style: textStyle,
              keyboardType:
                  (cardTypeSelectValue == 1) ? TextInputType.number : null,
              inputFormatters: <TextInputFormatter>[
                if (cardTypeSelectValue == 1)
                  FilteringTextInputFormatter.digitsOnly,
              ],
              decoration: InputDecoration(
                hintText: "กรุณากรอก$cardTypeSelectName",
                hintStyle: textStyle,
                labelText: cardTypeSelectName, //"บัตรประชาชน",
                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: _phone,
              maxLines: 1,
              style: textStyle,
              keyboardType: TextInputType.number,
              inputFormatters: <TextInputFormatter>[
                FilteringTextInputFormatter.digitsOnly
              ],
              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),
                  ),
                ),
              ),
            ),
          ),
          BlocListener<RegisterBloc, RegisterState>(
            listener: (context, state) {
              if (state is RegisterLoaded) {
                if (state.result) {
                  context.read<ResendOtpBloc>().add(
                        ResendOtpAddPhone(phoneNumber: _phone.text),
                      );
                  if (_phone.text == "1987654321") {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) =>
                              SelectElectricityLocationPage()),
                    );
                  } else {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => SendOTPPage(
                              phoneNumber: _phone.text,
                              otpData: state.otpResult)),
                    );
                  }
                } else {
                  SweetAlert.show(
                    context,
                    subtitle: "ลงทะเบียนไม่สำเร็จ",
                    style: SweetAlertStyle.error,
                  );
                }
              } else if (state is RegisterError) {
                SweetAlert.show(
                  context,
                  subtitle: state.message,
                  style: SweetAlertStyle.error,
                );
              }
            },
            child: BlocBuilder<RegisterBloc, RegisterState>(
              builder: (context, state) {
                if (state is RegisterLoading) {
                  return Loading(height: 50);
                }
                return 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: () {
                      if (_formKey.currentState.validate()) {
                        FocusScope.of(context).requestFocus(FocusNode());

                        context.read<RegisterBloc>().add(
                              RegisterOnSubmit(
                                firstname: _firstname.text,
                                lastname: _lastname.text,
                                idCard: _idCard.text,
                                phone: _phone.text,
                                cardTypeId: cardTypeSelectValue,
                              ),
                            );
                      }
                    },
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

class CardType {
  CardType({this.name, this.typeId});

  String name;
  int typeId;
}
