import 'dart:io';

import 'package:aitrainer_app/bloc/account/account_bloc.dart';
import 'package:aitrainer_app/bloc/login/login_bloc.dart';
import 'package:aitrainer_app/repository/user_repository.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar_min.dart';
import 'package:aitrainer_app/widgets/dialog_common.dart';
import 'package:aitrainer_app/widgets/dialog_long.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_bloc/flutter_form_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';

import '../library_keys.dart';

// ignore: must_be_immutable
class RegistrationPage extends StatelessWidget with Trans {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    final accountBloc = BlocProvider.of<AccountBloc>(context);
    setContext(context);
    return Scaffold(
        appBar: AppBarMin(),
        body: BlocProvider(
            create: (context) =>
                LoginBloc(userRepository: UserRepository(), accountBloc: accountBloc, context: context, isRegistration: true),
            child: BlocConsumer<LoginBloc, LoginState>(listener: (context, state) {
              if (state is LoginError) {
                String message = t(state.message);
                if (message == null) {
                  message = "";
                } else {
                  Scaffold.of(context).showSnackBar(
                      SnackBar(backgroundColor: Colors.orange, content: Text(message, style: TextStyle(color: Colors.white))));
                }
              } else if (state is LoginSuccess) {
                //Navigator.of(context).pushNamed('customerModifyPage');
                showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return DialogCommon(
                        title: t("Successful Registration"),
                        descriptions: t("Now we would like to know you better to lift the experience of the app."),
                        description2: t("Please go through the pages, it will take couple of minutes!"),
                        text: "OK",
                        onTap: () => {Navigator.of(context).pushNamed('customerModifyPage')},
                        onCancel: () => {
                          Navigator.of(context).pushNamed("home"),
                        },
                      );
                    });
              }
            }, builder: (context, state) {
              final loginBloc = BlocProvider.of<LoginBloc>(context);

              return ModalProgressHUD(
                child: loadForm(loginBloc, accountBloc),
                inAsyncCall: state is LoginLoading,
                opacity: 0.5,
                color: Colors.black54,
                progressIndicator: CircularProgressIndicator(),
              );
            })));
  }

  Widget loadForm(LoginBloc loginBloc, AccountBloc accountBloc) {
    return SafeArea(
      top: false,
      bottom: false,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('asset/image/WT_login.jpg'),
            fit: BoxFit.cover,
            alignment: Alignment.center,
          ),
        ),
        child: buildLoginForm(loginBloc, accountBloc),
      ),
    );
  }

  Widget buildLoginForm(LoginBloc loginBloc, AccountBloc accountBloc) {
    return Form(
      key: _scaffoldKey,
      child: Container(
          padding: const EdgeInsets.only(left: 20, right: 20),
          child: ListView(shrinkWrap: false, padding: EdgeInsets.only(top: 150.0), children: <Widget>[
            ListTile(title: Text(t("SignUp"), style: GoogleFonts.inter())),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FlatButton(
                  child: Image.asset(
                    'asset/image/button_fb.png',
                    width: 60,
                  ),
                  onPressed: () => {loginBloc.add(RegistrationFB())},
                ),
                Platform.isAndroid
                    ? FlatButton(
                        child: Image.asset(
                          'asset/image/button_google.png',
                          width: 60,
                        ),
                        onPressed: () => {loginBloc.add(RegistrationGoogle())},
                      )
                    : Offstage(),
                Platform.isIOS
                    ? FlatButton(
                        child: Image.asset(
                          'asset/image/button_apple.png',
                          width: 60,
                        ),
                        onPressed: () => {loginBloc.add(RegistrationApple())},
                      )
                    : Offstage(),
              ],
            ),
            ListTile(title: Text(t("OR"), style: GoogleFonts.inter())),
            TextFormField(
              key: LibraryKeys.loginEmailField,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.only(left: 15, top: 15, bottom: 15),
                labelText: t('Email'),
                fillColor: Colors.white24,
                filled: true,
                border: OutlineInputBorder(
                  gapPadding: 4.0,
                  borderRadius: BorderRadius.circular(12.0),
                  borderSide: BorderSide(color: Colors.green[50], width: 0.4),
                ),
              ),
              initialValue: loginBloc.userRepository.user.email,
              autovalidateMode: AutovalidateMode.onUserInteraction,
              validator: (val) {
                return t(loginBloc.emailValidation(val));
              },
              onChanged: (value) => loginBloc.add(LoginEmailChange(email: value)),
              keyboardType: TextInputType.emailAddress,
              style: new TextStyle(fontSize: 16, color: Colors.indigo),
            ),
            Divider(
              color: Colors.transparent,
            ),
            TextFormField(
              key: LibraryKeys.loginPasswordField,
              obscureText: loginBloc.obscure,
              decoration: InputDecoration(
                labelStyle: TextStyle(fontSize: 14),
                contentPadding: EdgeInsets.only(left: 15, top: 15, bottom: 15),
                suffixIcon: IconButton(
                  onPressed: () => {loginBloc.add(LoginPasswordChangeObscure())},
                  icon: Icon(Icons.remove_red_eye),
                ),
                labelText: t('Password'),
                fillColor: Colors.white24,
                filled: true,
                border: OutlineInputBorder(
                  gapPadding: 1.0,
                  borderRadius: BorderRadius.circular(12.0),
                  borderSide: BorderSide(color: Colors.green[50], width: 0.4),
                ),
              ),
              initialValue: loginBloc.userRepository.user.password,
              autovalidateMode: AutovalidateMode.always,
              validator: (val) {
                return t(loginBloc.passwordValidation(val));
              },
              onChanged: (value) => loginBloc.add(LoginPasswordChange(password: value)),
              keyboardType: TextInputType.visiblePassword,
              style: new TextStyle(fontSize: 16, color: Colors.indigo),
            ),
            Divider(
              color: Colors.transparent,
            ),
            getDataProtection(loginBloc),
            Divider(
              color: Colors.transparent,
            ),
            Row(mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[
              FlatButton(
                  key: LibraryKeys.loginOKButton,
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      Image.asset('asset/icon/gomb_zold_a.png', width: 140, height: 60),
                      Text(
                        t("OK"),
                        style: GoogleFonts.archivoBlack(fontSize: 20, color: Colors.white),
                      ),
                    ],
                  ),
                  //Image.asset('asset/icon/gomb_zold_b-1.png', width: 100, height: 100),
                  onPressed: () => {loginBloc.add(RegistrationSubmit())}),
            ]),
            Divider(
              color: Colors.transparent,
            ),
            Divider(
              color: Colors.transparent,
            ),
            Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[
              InkWell(
                child: Text(t('Login')),
                onTap: () => Navigator.of(context).pushNamed('login'),
              ),
              Spacer(flex: 2),
              InkWell(
                  child: Text(t('Privacy')),
                  onTap: () => {
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return DialogGDPR();
                            })
                      }),
            ]),
          ])),
    );
  }

  Widget getDataProtection(LoginBloc loginBloc) {
    return CheckboxListTile(
      title: Text(t("Please accept our data protection policy.")),
      subtitle: Text(t("For more information please click on 'Privacy'")),
      dense: true,
      value: loginBloc.dataPolicyAllowed,
      activeColor: Colors.indigo,
      onChanged: (value) {
        loginBloc.add(DataProtectionClicked(marked: value));
      },
      controlAffinity: ListTileControlAffinity.leading, //  <-- leading Checkbox
    );
  }
}