import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:validators/validators.dart' as validator;
import 'package:i18n_translate/i18n.dart';
import 'package:{{ name }}/repository/AuthenticationRepository.dart';

import 'package:{{ name }}/bloc/blocs.dart';

class LoginPage extends StatelessWidget {
  final AuthenticationRepository authenticationRepository;

  LoginPage({Key key, @required this.authenticationRepository})
      : assert(authenticationRepository != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: BlocProvider(
          create: (context) {
            return LoginBloc(
              authenticationBloc: BlocProvider.of<AuthenticationBloc>(context),
              authenticationRepository: authenticationRepository,
            );
          },
          child: LoginForm(),
        ),
      ),
    );
  }
}

class LoginForm extends StatefulWidget {
  @override
  State<LoginForm> createState() => _LoginFormState();
}

class _LoginFormState extends State<LoginForm> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _validate = false;
  bool _obscureText = true;
  bool _rememberMe = false;

  @override
  Widget build(BuildContext context) {
    _onLoginButtonPressed() {
      if (_formKey.currentState.validate()) {
        _formKey.currentState.validate();
        BlocProvider.of<LoginBloc>(context).add(
          LoginButtonPressed(
            email: _emailController.text,
            password: _passwordController.text,
            rememberMe: _rememberMe,
          ),
        );
      }
    }

    Widget _buildForgotPasswordBtn() {
      return Container(
        alignment: Alignment.centerRight,
        child: FlatButton(
          onPressed: () => Navigator.pushNamed(context, '/reset'),
          padding: EdgeInsets.only(right: 0.0),
          child: Text(
            I18n.translate(context, 'login.reset_password'),
            style: TextStyle(
              color: Color(0xff182779),
              fontWeight: FontWeight.bold,
              fontFamily: 'OpenSans',
            ),
          ),
        ),
      );
    }

    Widget _buildRememberMeCheckbox() {
      return Container(
        height: 20.0,
        child: Row(
          children: <Widget>[
            Theme(
              data: ThemeData(unselectedWidgetColor: Color(0xff0251ff)),
              child: Checkbox(
                value: _rememberMe,
                checkColor: Colors.white,
                activeColor: Color(0xff0251ff),
                onChanged: (value) {
                  setState(() {
                    _rememberMe = value;
                  });
                },
              ),
            ),
            Text(
              I18n.translate(context, 'login.keep_connected'),
              style: TextStyle(
                color: Color(0xff182779),
                fontWeight: FontWeight.bold,
                fontFamily: 'OpenSans',
              ),
            ),
          ],
        ),
      );
    }

    return BlocListener<LoginBloc, LoginState>(
      listener: (context, state) {
        if (state is LoginFailure) {
          Scaffold.of(context).showSnackBar(
            SnackBar(
              content: Text('${state.error}'),
              backgroundColor: Colors.red,
            ),
          );
        }
        if (state is LoginSuccces) {
          Navigator.of(context)
              .pushNamedAndRemoveUntil('/', (Route<dynamic> route) => false);
        }
      },
      child: BlocBuilder<LoginBloc, LoginState>(
        builder: (context, state) {
          return LayoutBuilder(builder: (context, constraints) {
            return SingleChildScrollView(
              child: ConstrainedBox(
                constraints: BoxConstraints(
                    minWidth: constraints.maxWidth,
                    minHeight: constraints.maxHeight),
                child: IntrinsicHeight(
                  child: Padding(
                    padding:
                        EdgeInsets.symmetric(horizontal: 30.0, vertical: 30.0),
                    child: Form(
                      key: _formKey,
                      autovalidate: _validate,
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            Text(I18n.translate(context, 'login.login'),
                                style: TextStyle(
                                  color: Color(0xff182779),
                                  fontFamily: 'CM Sans Serif',
                                  fontWeight: FontWeight.bold,
                                  fontSize: 32.0,
                                  height: 1.5,
                                )),
                            SizedBox(height: 20.0),
                            TextFormField(
                                keyboardType: TextInputType.emailAddress,
                                decoration: InputDecoration(
                                  labelText:
                                      I18n.translate(context, 'login.email'),
                                  prefixIcon: Icon(
                                    Icons.email,
                                    color: Color(0xff0251ff),
                                  ),
                                ),
                                controller: _emailController,
                                validator: (String value) {
                                  return validateEmail(context, value,
                                      I18n.translate(context, 'login.email'));
                                },
                                onSaved: (String val) {
                                  // email = val;
                                }),
                            TextFormField(
                              decoration: InputDecoration(
                                labelText:
                                    I18n.translate(context, 'login.password'),
                                prefixIcon: Icon(
                                  Icons.lock,
                                  color: Color(0xff0251ff),
                                ),
                                suffixIcon: IconButton(
                                  icon: Icon(
                                    // Based on passwordVisible state choose the icon
                                    _obscureText
                                        ? Icons.visibility
                                        : Icons.visibility_off,
                                    color: Color(0xff0251ff),
                                  ),
                                  onPressed: () {
                                    setState(() {
                                      _obscureText = !_obscureText;
                                    });
                                  },
                                ),
                              ),
                              controller: _passwordController,
                              obscureText: _obscureText,
                              validator: (String value) {
                                return validateRequired(context, value,
                                    I18n.translate(context, 'login.password'));
                              },
                            ),
                            Row(
                              children: <Widget>[
                                Expanded(child: _buildRememberMeCheckbox()),
                                Expanded(child: _buildForgotPasswordBtn()),
                              ],
                            ),
                            Expanded(
                              child: Container(),
                            ),
                            Container(
                              width: double.infinity,
                              child: RaisedButton(
                                color: Color(0xff0251ff),
                                padding: EdgeInsets.all(16.0),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(14.0),
                                ),
                                onPressed: state is! LoginLoading
                                    ? _onLoginButtonPressed
                                    : null,
                                child: Text(
                                  I18n.translate(context, 'login.login'),
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 18.0,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Text(
                                  I18n.translate(
                                      context, 'login.havent_account'),
                                  style: TextStyle(
                                    color: Color(0xff182779),
                                    fontFamily: 'OpenSans',
                                  ),
                                ),
                                FlatButton(
                                  onPressed: () =>
                                      Navigator.pushNamed(context, '/otp'),
                                  padding: EdgeInsets.all(0.0),
                                  child: Text(
                                    I18n.translate(context, 'login.register'),
                                    style: TextStyle(
                                      color: Color(0xff182779),
                                      fontWeight: FontWeight.bold,
                                      fontFamily: 'OpenSans',
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ]),
                    ),
                  ),
                ),
              ),
            );
          });
        },
      ),
    );
  }
}

String validateEmail(context, String value, String attribute) {
  if (value.length == 0) {
    return I18n.translate(
        context, 'validation.required', {"attribute": attribute});
  } else if (!validator.isEmail(value)) {
    return I18n.translate(
        context, 'validation.email', {"attribute": attribute});
  } else {
    return null;
  }
}

String validateRequired(context, String value, String attribute) {
  if (value.length == 0) {
    return I18n.translate(
        context, 'validation.required', {"attribute": attribute});
  } else {
    return null;
  }
}
