import 'package:app_hit_a_wod/src/blocs/login_form.bloc.dart';
import 'package:app_hit_a_wod/src/providers/auth.provider.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:app_hit_a_wod/src/styles.dart';
import 'package:flutter/services.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatelessWidget {
  const LoginPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final AuthProvider _auth = Provider.of<AuthProvider>(context);
    final LoginFormBloc bloc = LoginFormBloc(context, _auth);

    return GestureDetector(
      onTap: () {
        FocusScopeNode currentFocus = FocusScope.of(context);
        if (!currentFocus.hasPrimaryFocus) {
          currentFocus.unfocus();
        }
      },
      child: Container(
        decoration: BoxDecoration(
          gradient: neuGradient
        ),
        child: SafeArea(
          child: Scaffold(
            resizeToAvoidBottomPadding: false,
            backgroundColor: Colors.transparent,
            body: Container(
              height: MediaQuery.of(context).size.height,
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
              child: Column(
                children: <Widget>[
                  SizedBox(height: 50),
                  logo(),
                  SizedBox(height: 80),
                  Text("Iniciar sesión", style: Theme.of(context).textTheme.title),
                  SizedBox(height: 30),
                  emailInput(bloc),
                  SizedBox(height: 10),
                  passwordInput( bloc),
                  SizedBox(height: 10),
                  errorText(bloc),
                  Expanded(child: SizedBox()),
                  loginButton(bloc),
                  SizedBox(height: 20),
                  forgottenPasswordText(context),
                  SizedBox(height: 30),
                ],
              ),
            )
          )
        ),
      ),
    );
  }

  logo() => Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: <Widget>[
      Image(
        image: AssetImage("assets/icon/logo.png"),
        width: 100,
      ),
      SizedBox(height: 10),
      Image(
        image: AssetImage("assets/icon/nom.png"),
        width: 185,
      )
    ],
  );

  emailInput(LoginFormBloc bloc) => StreamBuilder(
    stream: bloc.emailStream,
    builder: (BuildContext context, AsyncSnapshot<String> data) {
      return neuInput(TextFormField(
        cursorColor: Color.fromRGBO(141, 39, 144, 1),
        keyboardType: TextInputType.emailAddress,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(vertical: 20, horizontal: 5),
          border: InputBorder.none,
          hintText: 'Tu correo electrónico'
        ),
        textInputAction: TextInputAction.send,
        onChanged: bloc.setEmail,
      ));
    }
  );

  passwordInput(LoginFormBloc bloc) => StreamBuilder(
    stream: bloc.passwordStream,
    builder: (BuildContext context, AsyncSnapshot<String> data) {
      return neuInput(TextFormField(
        obscureText: true,
        cursorColor: Color.fromRGBO(141, 39, 144, 1),
        keyboardType: TextInputType.visiblePassword,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(vertical: 20, horizontal: 5),
          border: InputBorder.none,
          hintText: 'Tu contraseña'
        ),
        textInputAction: TextInputAction.send,
        onChanged: bloc.setPassword,
      ));
    }
  );

  loginButton(LoginFormBloc bloc) {
    return StreamBuilder(
      initialData: 'init',
      stream: bloc.statusStream,
      builder: (BuildContext context, AsyncSnapshot<String> data) {
        //escoltem si arriba un token nou
        final status = data.hasData ? data.data : 'init';

        //info
        final childrenNormal = [
          Text("Iniciar sesión", style: Theme.of(context).textTheme.display2)
        ];
        final childrenLogging = [
          CircularProgressIndicator(strokeWidth: 3, backgroundColor: Colors.transparent, valueColor: new AlwaysStoppedAnimation<Color>(Color(0xFFF8F8FC)),)
        ];

        return NeumorphicButton(
          padding: EdgeInsets.symmetric(vertical: 25, horizontal: 20),
          boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(40)),
          style: NeumorphicStyle(
            color: colors['primary']
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: status=='loading' ? childrenLogging : childrenNormal
          ),
          onClick: () {
            if( status!='loading') { //si no hi ha token...
              bloc = LoginFormBloc(context, null);
              bloc.login();
            }
          }
        );
      }
    );
  }

  forgottenPasswordText(BuildContext context) => FlatButton(
    child: Text(
      "¿Has olvidado tu contraseña?", 
      style: Theme.of(context).textTheme.display1
    ),
    onPressed: (){
      Navigator.pushNamed(context, 'forgot-password');
    },
  );

  errorText(LoginFormBloc bloc) {
    return StreamBuilder(
      stream: bloc.statusStream,
      builder: (BuildContext context, AsyncSnapshot<String> data) {
        if(data.hasError) {
          if((data.error is String && (data.error as String).contains("DioErrorType.CONNECT_TIMEOUT")) || (data.error is DioError && (data.error as DioError).type==DioErrorType.CONNECT_TIMEOUT)) 
            return Text("No se ha podido conectar al servidor.", style: Theme.of(context).textTheme.display3, textAlign: TextAlign.center,);
          else 
            return Text(data.error.toString(), style: Theme.of(context).textTheme.display3, textAlign: TextAlign.center,);
        }
        else return Container();
      }
    );
  }

}