import 'package:app_hit_a_wod/src/blocs/change_password.bloc.dart';
import 'package:app_hit_a_wod/src/providers/api.provider.dart';
import 'package:app_hit_a_wod/src/styles.dart';
import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:provider/provider.dart';

class ChangePasswordPage extends StatelessWidget {

  ApiProvider _api;

  @override
  Widget build(BuildContext context) {

    ApiProvider _api = Provider.of<ApiProvider>(context);
    ChangePasswordBloc bloc = ChangePasswordBloc(context, _api);

    return GestureDetector(
      onTap: () {
        FocusScopeNode currentFocus = FocusScope.of(context);
        if (!currentFocus.hasPrimaryFocus) {
          currentFocus.unfocus();
        }
      },
      child: Container(
        decoration: BoxDecoration(
          gradient: neuGradient
        ),
        child: SafeArea(
          child: Scaffold(
            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(
                    "Revisa tu correo electrónico",
                    style: Theme.of(context).textTheme.title
                  ),
                  SizedBox(height: 30),
                  tokenInput(context, bloc),
                  SizedBox(height: 10),
                  passwordInput(context, bloc),
                  SizedBox(height: 10),
                  errorText(context, bloc),
                  Expanded(child: SizedBox()),
                  changePasswordButton(context, bloc),
                  SizedBox(height: 20),
                  iniciarSesionText(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,
      )
    ],
  );

  tokenInput(BuildContext context, ChangePasswordBloc bloc) => StreamBuilder(
    stream: bloc.tokenStream,
    builder: (context, snapshot) {
      return neuInput(TextFormField(
        keyboardType: TextInputType.text,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(vertical: 20, horizontal: 5),
          border: InputBorder.none,
          hintText: 'Código de recuperación recibido',
          errorText: snapshot.error
        ),
        textInputAction: TextInputAction.send,
        onChanged: bloc.setToken
      ));
    }
  );

  passwordInput(BuildContext context, ChangePasswordBloc bloc) => StreamBuilder(
    stream: bloc.passwordStream,
    builder: (context, snapshot) {
      return neuInput(TextFormField(
        obscureText: true,
        keyboardType: TextInputType.visiblePassword,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(vertical: 20, horizontal: 5),
          border: InputBorder.none,
          errorText: snapshot.error,
          hintText: 'Introduce tu nueva contraseña'
        ),
        textInputAction: TextInputAction.send,
        onChanged: bloc.setPassword,
      ));
    }
  );

  changePasswordButton(BuildContext context, ChangePasswordBloc bloc) {
    return StreamBuilder(
      initialData: 'init',
      stream: bloc.statusStream,
      builder: (BuildContext context, AsyncSnapshot<String> data) {
        final status = data.hasData ? data.data : 'init';

        //info
        final childrenNormal = [
          Text("Cambiar contraseña", 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: () async {
            if(status!="loading") {
              bool resp = await bloc.resetPassword();
              if(!resp) {
                bloc.setPassword("");
              }
            }
          }
        );
      }
    );
 
  }

  iniciarSesionText(BuildContext context) => FlatButton(
    child: Text(
      "Volver", 
      style: Theme.of(context).textTheme.display1
    ),
    onPressed: (){
      Navigator.pushReplacementNamed(context, 'login');
    },
  );

  errorText(BuildContext context, ChangePasswordBloc bloc) {
    return StreamBuilder(
      stream: bloc.statusStream,
      builder: (BuildContext context, AsyncSnapshot<String> data) {
        if(data.hasError) {
          return Text(data.error.toString(), style: Theme.of(context).textTheme.display3);
        }
        else return Container();
      }
    );
  }
}