import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/http_status_manger.dart';
import 'package:test_sa/controllers/localization/localization.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_provider.dart';
import 'package:test_sa/controllers/validator/validator.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/models/user.dart';
import 'package:test_sa/views/widgets/app_text_form_field.dart';
import 'package:test_sa/views/widgets/buttons/app_back_button.dart';
import 'package:test_sa/views/widgets/buttons/app_button.dart';
import 'package:test_sa/views/widgets/departments/department_button.dart';
import 'package:test_sa/views/widgets/hospitals/hospital_button.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';

class Register extends StatefulWidget {
  static final String id = "/register";

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

class _RegisterState extends State<Register> {
  UserProvider _userProvider;
  SettingProvider _settingProvider;
  double _width;
  double _height;
  User _user = User();
  bool _obscurePassword = true;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _width = MediaQuery.of(context).size.width;
    _height = MediaQuery.of(context).size.height;
    Subtitle _subtitle = AppLocalization.of(context).subtitle;
    return Scaffold(
      key: _scaffoldKey,
      body: LoadingManager(
        isLoading: _userProvider.isLoading,
        isFailedLoading: false,
        stateCode: 200,
        onRefresh: () async {},
        child: SafeArea(
          child: Stack(
            children: [
              Form(
                key: _formKey,
                child: ListView(
                  padding: const EdgeInsets.all(20),
                  children: [
                    //AppNameBar(),
                    //SizedBox(height: 16,),
                    Hero(
                      tag: "logo",
                      child: Padding(
                        padding: const EdgeInsets.all(16),
                        child: Image(
                          height: _height / 6,
                          image: AssetImage("assets/images/logo.png"),
                        ),
                      ),
                    ),
                    ATextFormField(
                      initialValue: _user.userName,
                      hintText: _subtitle.name,
                      prefixIconData: Icons.account_circle,
                      style: Theme.of(context).textTheme.headline6,
                      validator: (value) => Validator.hasValue(value) ? null : _subtitle.nameValidateMessage,
                      onSaved: (value) {
                        _user.userName = value;
                      },
                    ),
                    const SizedBox(height: 12),
                    ATextFormField(
                      initialValue: _user.email,
                      hintText: _subtitle.email,
                      prefixIconData: Icons.email,
                      textInputType: TextInputType.emailAddress,
                      style: Theme.of(context).textTheme.headline6,
                      validator: (value) => Validator.isEmail(value) ? null : _subtitle.emailValidateMessage,
                      onSaved: (value) {
                        _user.email = value;
                      },
                    ),
                    const SizedBox(height: 12),
                    ATextFormField(
                      initialValue: _user.password,
                      hintText: _subtitle.password,
                      prefixIconData: Icons.vpn_key_sharp,
                      style: Theme.of(context).textTheme.headline6,
                      obscureText: _obscurePassword,
                      validator: (value) => Validator.isValidPassword(value) ? null : _subtitle.passwordValidateMessage,
                      showPassword: () {
                        _obscurePassword = !_obscurePassword;
                        setState(() {});
                      },
                      onSaved: (value) {
                        _user.password = value;
                      },
                      onChange: (value) {
                        _user.password = value;
                      },
                    ),
                    const SizedBox(height: 12),
                    ATextFormField(
                      initialValue: _user.password,
                      prefixIconData: Icons.vpn_key_sharp,
                      hintText: _subtitle.confirmPassword,
                      style: Theme.of(context).textTheme.headline6,
                      obscureText: _obscurePassword,
                      validator: (value) => _user.password == value ? null : _subtitle.confirmPasswordValidateMessage,
                      showPassword: () {
                        _obscurePassword = !_obscurePassword;
                        setState(() {});
                      },
                    ),
                    const SizedBox(height: 12),
                    HospitalButton(
                      hospital: _user.hospital,
                      onHospitalPick: (hospital) {
                        _user.hospital = hospital;
                        setState(() {});
                      },
                    ),
                    const SizedBox(height: 12),
                    DepartmentButton(
                      department: _user.department,
                      onDepartmentPick: (department) {
                        _user.department = department;
                        setState(() {});
                      },
                    ),
                    const SizedBox(height: 12),
                    ATextFormField(
                      initialValue: _user.phoneNumber,
                      hintText: _subtitle.phoneNumber,
                      style: Theme.of(context).textTheme.headline6,
                      prefixIconData: Icons.phone_android,
                      validator: (value) => Validator.isPhoneNumber(value) ? null : _subtitle.phoneNumberValidateMessage,
                      textInputType: TextInputType.phone,
                      onSaved: (value) {
                        _user.phoneNumber = value;
                      },
                    ),
                    SizedBox(height: 8),
                    ATextFormField(
                      initialValue: _user.whatsApp,
                      hintText: _subtitle.whatsApp,
                      style: Theme.of(context).textTheme.headline6,
                      prefixIconData: FontAwesomeIcons.whatsapp,
                      prefixIconSize: 36,
                      validator: (value) => Validator.isPhoneNumber(value) ? null : _subtitle.phoneNumberValidateMessage,
                      textInputType: TextInputType.phone,
                      onSaved: (value) {
                        _user.whatsApp = value;
                      },
                    ),
                    const SizedBox(height: 12),
                    AButton(
                      text: _subtitle.signUp,
                      onPressed: () async {
                        if (!_formKey.currentState.validate()) return;
                        _formKey.currentState.save();
                        if (_user.hospital == null) {
                          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            content: Text(_subtitle.hospitalRequired),
                          ));
                          return;
                        }
                        if (_user.department == null) {
                          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            content: Text(_subtitle.unitRequired),
                          ));
                          return;
                        }
                        int status = await _userProvider.register(
                          user: _user,
                          host: _settingProvider.host,
                        );
                        if (status >= 200 && status < 300) {
                          Fluttertoast.showToast(msg: _subtitle.activationAlert);
                          Navigator.of(context).pop();
                        } else {
                          String errorMessage = status == 402
                              ? _subtitle.nameExist
                              : status == 401
                                  ? _subtitle.emailExist
                                  : HttpStatusManger.getStatusMessage(status: status, subtitle: _subtitle);
                          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            content: Text(errorMessage),
                          ));
                        }
                      },
                    ),
                  ],
                ),
              ),
              ABackButton(),
            ],
          ),
        ),
      ),
    );
  }
}
