import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:peasmartcare/blocs/profile/profile_bloc.dart';
import 'package:peasmartcare/components/body_layout.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/components/profile_avatar.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/constraints/image_asset.dart';
import 'package:peasmartcare/models/coordinator_position_model.dart';
import 'package:peasmartcare/models/profile_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/widgets/empty_box.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';

class ProfilePage extends StatefulWidget {
  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final _formKey = GlobalKey<FormState>();
  TextEditingController _position = TextEditingController();
  TextEditingController _phone = TextEditingController();
  TextEditingController _otherContact = TextEditingController();
  String _firstname = "";
  String _lastname = "";
  String _fullname = "";
  String _idCard = "";
  // String _positionValue;
  // String _positionName;

  @override
  void initState() {
    context.read<ProfileBloc>().add(ProfileGetData());
    super.initState();
  }

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

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PEAAppBar(
        title: "แก้ไขข้อมูลส่วนตัว",
        actions: <Widget>[
          ProfileAvatar(disableEditProfile: true),
        ],
      ),
      body: BodyLayout(
        top: 0,
        layoutType: LayoutType.ONLY_CHILD,
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                _body(),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _body() {
    TextStyle textStyle = TextStyle(color: Color(AppData.purpleColor), fontSize: 18);
    TextStyle textLabelStyle = TextStyle(color: Color(AppData.purpleColor), fontSize: 20, fontWeight: FontWeight.bold);
    TextStyle errortyle = TextStyle(color: Colors.orange[900], fontSize: 18, height: 0.6);
    // List<CoordinatorPositionModel> _positionList = List<CoordinatorPositionModel>();

    // _positionList.add(CoordinatorPositionModel(id: "1", name: "ผู้จัดการ"));
    // _positionList.add(CoordinatorPositionModel(id: "2", name: "โปรแกรมเมอร์"));
    // _positionList.add(CoordinatorPositionModel(id: "3", name: "ผู้ช่วยผู้จัดการ"));

    return BlocListener<ProfileBloc, ProfileState>(
      listener: (context, state) {
        if (state is ProfileLoaded) {
          if (state.saveSuccess != null && state.saveSuccess) {
            SweetAlert.show(
              context,
              subtitle: "บันทึกสำเร็จ",
              style: SweetAlertStyle.success,
              showCancelButton: false,
              onPress: (bool isConfirm) {
                context.read<ProfileBloc>().add(ProfileGetData());

                Navigator.pop(context);

                return false;
              },
            );
          } else if (state.saveSuccess != null && !state.saveSuccess) {
            SweetAlert.show(
              context,
              subtitle: "บันทึกไม่สำเร็จ",
              style: SweetAlertStyle.error,
            );
          }

          if (state.saveSuccess == null) {
            ProfileModel profile = state.result;
            setState(() {
              _firstname = profile.firstname;
              _lastname = profile.lastname;
              _fullname = "${profile.firstname} ${profile.lastname}";
              _idCard = profile.idCard ?? "";
              _position.text = profile.position;
              _phone.text = profile.phone;
              _otherContact.text = profile.contactOther;
            });
          }
        } else if (state is ProfileErrorUnauthorized) {
          Navigator.of(context).popUntil((route) => route.isFirst);
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => LogoutPage()),
          );
        }
      },
      child: BlocBuilder<ProfileBloc, ProfileState>(
        builder: (context, state) {
          if (state is ProfileLoading) {
            return Loading();
          } else if (state is ProfileLoaded) {
            return Positioned(
              child: Padding(
                padding: const EdgeInsets.only(top: 40),
                child: Container(
                  // height: 800,
                  child: Center(
                    child: Column(
                      children: <Widget>[
                        _buildAvatar(ImageAsset.imageDefaultAvartar),
                        SizedBox(height: 50),
                        Text(
                          _fullname,
                          style: TextStyle(
                            color: Color(AppData.purpleColor),
                            fontSize: 30,
                          ),
                        ),
                        SizedBox(height: 40),
                        Form(
                          key: _formKey,
                          child: Container(
                            constraints: BoxConstraints(maxWidth: 500),
                            child: Column(
                              children: <Widget>[
                                Container(
                                  height: 100,
                                  width: double.infinity,
                                  padding: EdgeInsets.only(left: 25, right: 25),
                                  child: Card(
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(30),
                                    ),
                                    color: Color(AppData.whiteColor),
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                                      child: Column(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Text("บัตรประชาชน", style: textLabelStyle),
                                          SizedBox(height: 5),
                                          Text(_idCard, style: textStyle),
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(height: 25),
                                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(
                                      suffixIcon: Icon(Icons.edit),
                                      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: _phone,
                                    maxLines: 1,
                                    style: textStyle,
                                    keyboardType: TextInputType.number,
                                    inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly],
                                    decoration: InputDecoration(
                                      suffixIcon: Icon(Icons.edit),
                                      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(
                                      suffixIcon: Icon(Icons.edit),
                                      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: () {
                                  if (_formKey.currentState.validate()) {
                                    context.read<ProfileBloc>().add(
                                          ProfileOnSubmit(
                                            firstname: _firstname,
                                            lastname: _lastname,
                                            idCard: _idCard,
                                            position: _position.text,
                                            phone: _phone.text,
                                            otherContact: _otherContact.text,
                                          ),
                                        );
                                  }
                                },
                              ),
                            ),
                            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.of(context).popUntil((route) => route.isFirst);
                                },
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            );
          }

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

  CircleAvatar _buildAvatar(String image, {double radius = 80}) {
    return CircleAvatar(
      backgroundColor: Colors.white,
      radius: radius,
      child: CircleAvatar(
        radius: radius - 2,
        backgroundImage: AssetImage(image), //NetworkImage(image),
      ),
    );
  }
}
