import 'package:farm_tpf/custom_model/LocationUnit.dart';
import 'package:farm_tpf/custom_model/account.dart';
import 'package:farm_tpf/data/repository/user_repository.dart';
import 'package:farm_tpf/presentation/custom_widgets/app_bar_widget.dart';
import 'package:farm_tpf/presentation/custom_widgets/button_widget.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_loading.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_toast.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_utils.dart';
import 'package:farm_tpf/presentation/screens/actions/state_management_helper/change_supply.dart';
import 'package:farm_tpf/presentation/screens/location_unit/sc_location.dart';
import 'package:farm_tpf/presentation/screens/profile/controller/check_change_another_dropdown.dart';
import 'package:farm_tpf/presentation/screens/profile/sc_change_password.dart';
import 'package:farm_tpf/utils/const_color.dart';
import 'package:farm_tpf/utils/const_common.dart';
import 'package:farm_tpf/utils/const_string.dart';
import 'package:farm_tpf/utils/const_style.dart';
import 'package:farm_tpf/utils/validators.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';
import 'package:package_info/package_info.dart';

import 'bloc_get_account.dart';

class UpdateProfileScreen extends StatefulWidget {
  static Route route() {
    return MaterialPageRoute<void>(builder: (_) => UpdateProfileScreen());
  }

  @override
  _UpdateProfileScreenState createState() => _UpdateProfileScreenState();
}

class _UpdateProfileScreenState extends State<UpdateProfileScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final _repository = UserRepository();
  GlobalKey<FormState> _formKey = GlobalKey();
  bool _autoValidate = false;

  Account _account = Account();
  TextEditingController _userNameController = TextEditingController();
  TextEditingController _fullNameController = TextEditingController();
  TextEditingController _emailController = TextEditingController();
  TextEditingController _addressController = TextEditingController();
  var checkChangeLocation = Get.put(CheckChangeAnotherDropdown());

  @override
  void initState() {
    super.initState();
    checkChangeLocation.initValue();
    getAccountBloc.getAccount((data) {
      _account = data;
      _userNameController.text = _account.login ?? '';
      _fullNameController.text = _account.fullName.toString();
      _emailController.text = _account.email.toString();
      _addressController.text = _account.address ?? '';
      checkChangeLocation.changeCountryByIdAndName(_account.countryId?.toInt() ?? -1, _account.countryName ?? '');
      checkChangeLocation.changeProvinceByIdAndName(_account.cityId?.toInt() ?? -1, _account.cityName ?? '');
      checkChangeLocation.changeDistrictByIdAndName(_account.districtId?.toInt() ?? -1, _account.districtName ?? '');
      checkChangeLocation.changeWardByIdAndName(_account.wardId?.toInt() ?? -1, _account.wardName ?? '');
    }, (err) {
      Utils.showSnackBarError(message: "Lỗi tải dữ liệu");
    });
  }

  _validateInputs() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      _account.countryId = checkChangeLocation.currentCountry.id;
      _account.cityId = checkChangeLocation.currentProvince.id;
      _account.districtId = checkChangeLocation.currentDistrict.id;
      _account.wardId = checkChangeLocation.currentWard.id;
      LoadingDialog.showLoadingDialog(_scaffoldKey.currentContext!);
      _repository.updateProfile(_account).then((value) {
        LoadingDialog.hideLoadingDialog(_scaffoldKey.currentContext!);
        Utils.showSnackBarSuccess(message: 'Cập nhật thành công.');
      }).catchError((onError) {
        Utils.showSnackBarError(message: 'Cập nhật không thành công.');
        LoadingDialog.hideLoadingDialog(_scaffoldKey.currentContext!);
        print("error");
      });
    } else {
      _autoValidate = true;
    }
  }

  Widget _userNameField() {
    return TextFormField(
      keyboardType: TextInputType.text,
      enabled: false,
      decoration: const InputDecoration(labelText: "Tài khoản"),
      controller: _userNameController,
      validator: (String? value) {
        return Validators.validateNotNullOrEmpty(value ?? '', "Tài khoản");
      },
      onSaved: (newValue) {},
    );
  }

  Widget _fullNameField() {
    return TextFormField(
      keyboardType: TextInputType.text,
      decoration: const InputDecoration(labelText: "Họ và tên"),
      controller: _fullNameController,
      validator: (String? value) {
        return Validators.validateNotNullOrEmpty(value ?? '', "Họ và tên");
      },
      onSaved: (newValue) {
        _account.fullName = newValue ?? '';
      },
    );
  }

  Widget _emailField() {
    return TextFormField(
      keyboardType: TextInputType.emailAddress,
      decoration: const InputDecoration(labelText: "Email"),
      controller: _emailController,
      validator: (String? value) {
        return Validators.validateEmail(value ?? '');
      },
      onSaved: (newValue) {
        _account.email = newValue ?? '';
      },
    );
  }

  Widget _btnSelectCountry() {
    return GetBuilder<CheckChangeAnotherDropdown>(builder: (data) {
      return FlatButton(
          padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
          onPressed: () {
            if (Get.isSnackbarOpen) {
              Get.back();
            }
            Navigator.of(context)
                .push(MaterialPageRoute(
                    builder: (_) => LocationScreen(
                          titleName: "Quốc gia",
                          type: LocationType.country,
                          filterId: -1,
                          selectedId: checkChangeLocation.currentCountry.id ?? -1,
                        ),
                    fullscreenDialog: false))
                .then((value) {
              if (value != null) {
                var result = value as LocationUnit;
                checkChangeLocation.changeCountry(result);
              }
            });
          },
          child: Container(
              padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 10.5, left: 0.0),
              decoration: const BoxDecoration(
                border: kBorderTextField,
              ),
              child: Row(
                children: [
                  GetBuilder<ChangeSupply>(
                      builder: (_) => Expanded(
                          child: Text(checkChangeLocation.currentCountry.name ?? "Quốc gia",
                              style: const TextStyle(fontSize: 14.0, color: Colors.black87)))),
                  const Icon(
                    Icons.arrow_drop_down,
                    color: Colors.grey,
                  ),
                ],
              )));
    });
  }

  Widget _btnSelectProvince() {
    return GetBuilder<CheckChangeAnotherDropdown>(builder: (data) {
      return FlatButton(
          padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
          onPressed: () {
            if (Get.isSnackbarOpen) {
              Get.back();
            }
            if (checkChangeLocation.currentCountry.id != null) {
              Navigator.of(context)
                  .push(MaterialPageRoute(
                      builder: (_) => LocationScreen(
                            titleName: "Tỉnh/Thành phố",
                            type: LocationType.province,
                            filterId: checkChangeLocation.currentCountry.id ?? -1,
                            selectedId: checkChangeLocation.currentProvince.id ?? -1,
                          ),
                      fullscreenDialog: false))
                  .then((value) {
                if (value != null) {
                  var result = value as LocationUnit;
                  checkChangeLocation.changeProvince(result);
                }
              });
            } else {
              Utils.showSnackBarWarning(message: label_country_empty);
            }
          },
          child: Container(
              padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 10.5, left: 0.0),
              decoration: const BoxDecoration(
                border: kBorderTextField,
              ),
              child: Row(
                children: [
                  GetBuilder<ChangeSupply>(
                      builder: (_) => Expanded(
                          child: Text(checkChangeLocation.currentProvince.name ?? "Tỉnh/Thành Phố",
                              style: const TextStyle(fontSize: 14.0, color: Colors.black87)))),
                  const Icon(
                    Icons.arrow_drop_down,
                    color: Colors.grey,
                  ),
                ],
              )));
    });
  }

  Widget _btnSelectDistrict() {
    return GetBuilder<CheckChangeAnotherDropdown>(builder: (data) {
      return FlatButton(
          padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
          onPressed: () {
            if (Get.isSnackbarOpen) Get.back();
            if (checkChangeLocation.currentProvince.id != null) {
              Navigator.of(context)
                  .push(MaterialPageRoute(
                      builder: (_) => LocationScreen(
                            titleName: "Quận/Huyện",
                            type: LocationType.district,
                            filterId: checkChangeLocation.currentProvince.id ?? -1,
                            selectedId: checkChangeLocation.currentDistrict.id ?? -1,
                          ),
                      fullscreenDialog: false))
                  .then((value) {
                if (value != null) {
                  var result = value as LocationUnit;
                  checkChangeLocation.changeDistrict(result);
                }
              });
            } else {
              Utils.showSnackBarWarning(message: label_province_empty);
            }
          },
          child: Container(
              padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 10.5, left: 0.0),
              decoration: const BoxDecoration(
                border: kBorderTextField,
              ),
              child: Row(
                children: [
                  GetBuilder<ChangeSupply>(
                      builder: (_) => Expanded(
                          child: Text(checkChangeLocation.currentDistrict.name ?? "Quận/Huyện",
                              style: const TextStyle(fontSize: 14.0, color: Colors.black87)))),
                  const Icon(
                    Icons.arrow_drop_down,
                    color: Colors.grey,
                  ),
                ],
              )));
    });
  }

  Widget _btnSelectWard() {
    return GetBuilder<CheckChangeAnotherDropdown>(builder: (data) {
      return FlatButton(
          padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
          onPressed: () {
            if (Get.isSnackbarOpen) Get.back();
            if (checkChangeLocation.currentDistrict.id != null) {
              Navigator.of(context)
                  .push(MaterialPageRoute(
                      builder: (_) => LocationScreen(
                            titleName: "Phường/Xã",
                            type: LocationType.ward,
                            filterId: checkChangeLocation.currentDistrict.id ?? -1,
                            selectedId: checkChangeLocation.currentWard.id ?? -1,
                          ),
                      fullscreenDialog: false))
                  .then((value) {
                if (value != null) {
                  var result = value as LocationUnit;
                  checkChangeLocation.changeWard(result);
                }
              });
            } else {
              Utils.showSnackBarWarning(message: label_district_empty);
            }
          },
          child: Container(
              padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 10.5, left: 0.0),
              decoration: const BoxDecoration(
                border: kBorderTextField,
              ),
              child: Row(
                children: [
                  GetBuilder<ChangeSupply>(
                      builder: (_) => Expanded(
                          child: Text(checkChangeLocation.currentWard.name ?? "Phường/Xã",
                              style: const TextStyle(fontSize: 14.0, color: Colors.black87)))),
                  const Icon(
                    Icons.arrow_drop_down,
                    color: Colors.grey,
                  ),
                ],
              )));
    });
  }

  Widget _addressField() {
    return TextFormField(
      keyboardType: TextInputType.text,
      decoration: const InputDecoration(labelText: "Địa chỉ"),
      controller: _addressController,
      onSaved: (newValue) {
        _account.address = newValue ?? '';
      },
    );
  }

  @override
  Widget build(BuildContext context) => KeyboardDismisser(
      child: Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBarWidget(
            isBack: true,
            action: InkWell(
              child: const Text(
                'Huỷ',
                style: TextStyle(color: Colors.red, fontWeight: FontWeight.normal),
              ),
              onTap: () {
                if (Get.isSnackbarOpen) Get.back();
                Get.back();
              },
            ),
          ),
          key: _scaffoldKey,
          body: _buildContent()));

  Widget _buildContent() {
    return StreamBuilder(
        stream: getAccountBloc.actions,
        builder: (context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.hasData) {
            return Form(
                key: _formKey,
                // autovalidate: _autoValidate,
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      const Text(
                        'Tài khoản',
                        style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22),
                      ),
                      _userNameField(),
                      const SizedBox(
                        height: 8.0,
                      ),
                      _fullNameField(),
                      const SizedBox(
                        height: 8.0,
                      ),
                      _emailField(),
                      const SizedBox(
                        height: 8.0,
                      ),
                      Container(
                        width: double.infinity,
                        child: const Text(
                          "Quốc gia",
                          style: TextStyle(color: Colors.black54, fontSize: 13.0),
                        ),
                      ),
                      _btnSelectCountry(),
                      Container(
                        width: double.infinity,
                        child: const Text(
                          "Tỉnh/Thành phố",
                          style: TextStyle(color: Colors.black54, fontSize: 13.0),
                        ),
                      ),
                      _btnSelectProvince(),
                      Container(
                        width: double.infinity,
                        child: const Text(
                          "Quận/Huyện",
                          style: TextStyle(color: Colors.black54, fontSize: 13.0),
                        ),
                      ),
                      _btnSelectDistrict(),
                      Container(
                        width: double.infinity,
                        child: const Text(
                          "Phường/Xã",
                          style: TextStyle(color: Colors.black54, fontSize: 13.0),
                        ),
                      ),
                      _btnSelectWard(),
                      const SizedBox(
                        height: 8.0,
                      ),
                      _addressField(),
                      const SizedBox(
                        height: 16.0,
                      ),
                      ButtonWidget(
                          title: 'CẬP NHẬT',
                          onPressed: () {
                            var currentFocus = FocusScope.of(context);
                            if (!currentFocus.hasPrimaryFocus) {
                              currentFocus.unfocus();
                            }
                            _validateInputs();
                          }),
                    ],
                  ),
                ));
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        });
  }

  @override
  void dispose() {
    super.dispose();
    _userNameController.dispose();
    _emailController.dispose();
    _fullNameController.dispose();
    _addressController.dispose();
  }
}
