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 LoginPage 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: false),
            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) {
                Navigator.of(context).pushNamed('home');
              } else if (state is LoginSkipped) {
                showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return DialogCommon(
                        title: t("No Login"),
                        descriptions: t("You will skip the login."),
                        description2: t("The app functionalitity will be restricted, but please take a tour!"),
                        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: 140,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextButton(
                  child: Image.asset(
                    'asset/image/button_fb.png',
                    width: 60,
                  ),
                  onPressed: () => {loginBloc.add(LoginFB())},
                ),
                Platform.isAndroid
                    ? TextButton(
                        child: Image.asset(
                          'asset/image/button_google.png',
                          width: 60,
                        ),
                        onPressed: () => {loginBloc.add(LoginGoogle())},
                      )
                    : Offstage(),
                Platform.isIOS
                    ? TextButton(
                        child: Image.asset(
                          'asset/image/button_apple.png',
                          width: 60,
                        ),
                        onPressed: () => {loginBloc.add(LoginApple())},
                      )
                    : Offstage(),
              ],
            ),
            Divider(),
            SizedBox(
              height: 50,
            ),
            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) {
                String? validationText = loginBloc.emailValidation(val);
                return validationText == null ? null : t(validationText);
              },
              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) {
                String? validationText = loginBloc.passwordValidation(val);
                return validationText == null ? null : t(validationText);
              },
              onChanged: (value) => loginBloc.add(LoginPasswordChange(password: value)),
              keyboardType: TextInputType.visiblePassword,
              style: new TextStyle(fontSize: 16, color: Colors.indigo),
            ),
            Divider(
              color: Colors.transparent,
            ),
            Row(mainAxisAlignment: MainAxisAlignment.end, 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(LoginSubmit())}),
            ]),
            SizedBox(
              height: 50,
            ),
            Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[
              InkWell(
                child: Text(
                  t('SignUpLink'),
                  style: GoogleFonts.inter(color: Colors.black, decoration: TextDecoration.underline),
                ),
                onTap: () => Navigator.of(context).pushNamed('registration'),
              ),
              Spacer(flex: 2),
              InkWell(
                child: Text(
                  t('I forgot the password'),
                  style: GoogleFonts.inter(color: Colors.black, decoration: TextDecoration.underline),
                ),
                onTap: () => Navigator.of(context).pushNamed('resetPassword'),
              ),
              Spacer(flex: 2),
              InkWell(
                  child: Text(
                    t('Privacy'),
                    style: GoogleFonts.inter(color: Colors.black, decoration: TextDecoration.underline),
                  ),
                  onTap: () => {
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return DialogGDPR();
                            })
                      }),
            ]),
          ])),
    );
  }
}
