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:google_fonts/google_fonts.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.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) {
                ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(backgroundColor: Colors.orange, content: Text(t(state.message), style: TextStyle(color: Colors.white))));
              } else if (state is LoginSuccess) {
                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"),
                        },
                      );
                    });
              } else if (state is LoginSkipped) {
                showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return DialogCommon(
                        title: t("No Registration"),
                        descriptions: t("You will skip the registration process."),
                        description2: t("Please take a short tour in the app"),
                        text: "OK",
                        onTap: () => {Navigator.of(context).pushNamed('home')},
                        onCancel: () => {
                          Navigator.of(context).pop(),
                        },
                      );
                    });
              }
            }, 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: 10.0), children: <Widget>[
            GestureDetector(
                onTap: () => loginBloc.add(LoginSkip()),
                child: Text(
                  t("Skip"),
                  textAlign: TextAlign.right,
                  style: GoogleFonts.inter(color: Colors.black, decoration: TextDecoration.underline),
                )),
            SizedBox(
              height: 120,
            ),
            ListTile(title: Text(t("SignUp"), style: GoogleFonts.inter())),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextButton(
                  child: Image.asset(
                    'asset/image/button_fb.png',
                    width: 60,
                  ),
                  onPressed: () => {loginBloc.add(RegistrationFB())},
                ),
                Platform.isAndroid
                    ? TextButton(
                        child: Image.asset(
                          'asset/image/button_google.png',
                          width: 60,
                        ),
                        onPressed: () => {loginBloc.add(RegistrationGoogle())},
                      )
                    : Offstage(),
                Platform.isIOS
                    ? TextButton(
                        child: Image.asset(
                          'asset/image/button_apple.png',
                          width: 60,
                        ),
                        onPressed: () => {loginBloc.add(RegistrationApple())},
                      )
                    : Offstage(),
              ],
            ),
            //ListTile(title: Text(t("OR"), style: GoogleFonts.inter())),
            Divider(
              color: Colors.transparent,
            ),
            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) {
                final String? validator = loginBloc.emailValidation(val!);
                return validator == null ? null : t(validator);
              },
              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.onUserInteraction,
              validator: (val) {
                final String? validator = loginBloc.passwordValidation(val!);
                return validator == null ? null : t(validator);
              },
              onChanged: (value) => loginBloc.add(LoginPasswordChange(password: value)),
              keyboardType: TextInputType.visiblePassword,
              style: new TextStyle(fontSize: 16, color: Colors.indigo),
            ),
            Divider(
              color: Colors.transparent,
            ),
            getDataProtection(loginBloc),
            getEmailSubscription(loginBloc),
            Divider(
              color: Colors.transparent,
            ),
            Row(mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[
              TextButton(
                  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'),
                  style: GoogleFonts.inter(decoration: TextDecoration.underline),
                ),
                onTap: () => Navigator.of(context).pushNamed('login'),
              ),
              Spacer(flex: 2),
              InkWell(
                  child: Text(
                    t('Privacy'),
                    style: GoogleFonts.inter(decoration: TextDecoration.underline),
                  ),
                  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
    );
  }

  Widget getEmailSubscription(LoginBloc loginBloc) {
    return CheckboxListTile(
      title: Text(t("Email notifications")),
      subtitle: Text(t("We may ask you about your opinion, send events in email")),
      dense: true,
      value: loginBloc.emailSubscription,
      activeColor: Colors.indigo,
      onChanged: (value) {
        loginBloc.add(EmailSubscriptionClicked(marked: value!));
      },
      controlAffinity: ListTileControlAffinity.leading, //  <-- leading Checkbox
    );
  }
}
