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

import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';

import 'package:imagini/blocs/login_bloc.dart';
import 'package:imagini/core/app_provider.dart';

class LoginScreen extends StatefulWidget {
  static const String PATH = '/';

  LoginScreen({Key key}) : super(key: key);

  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {

  LoginBloc bloc;

  @override
  Widget build(BuildContext context) {
    _init();

    return Scaffold(
      body: StreamBuilder<bool>(
        stream: bloc.authenticatedResult,
        builder: (context, snapshot) {
          if (snapshot.data == null || snapshot.data == true)
            return _appLoading();
          return _appLogin();
        }
      )
    );
  }

  void _init(){
    if(bloc != null)
        return;

    bloc = LoginBloc(AppProvider.getApplication(context));
    bloc.authenticatedResult.listen((bool status) {
      if (status)
        AppProvider.getRouter(context).navigateTo(context, "/Home", transition: TransitionType.fadeIn);
    });

    bloc.loginResult.listen((bool status) {
      if (status == null || status == false)
        return;

      AppProvider.getRouter(context).navigateTo(context, "/Home", transition: TransitionType.fadeIn);
    });
  }

  @override
  void dispose() {
    super.dispose();
    // bloc.dispose();
  }

  Widget _appLoading(){
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 500),
        child: Container(
          margin: EdgeInsets.fromLTRB(50, 0, 50, 0),
          height: 270,
          child: Column(
            children: <Widget>[
              Container(
                child: FittedBox(
                  fit: BoxFit.contain,
                  child: const FlutterLogo(),
                ),
                width: 175,
                margin: EdgeInsets.fromLTRB(0, 0, 0, 50),
              ),
              PlatformCircularProgressIndicator()
            ],
          ),
        ),
      ),
    );
  }

  Widget _appLogin(){
    TextEditingController serverController = new TextEditingController();
    TextEditingController userController = new TextEditingController();
    TextEditingController passwordController = new TextEditingController();

    final _formKey = GlobalKey<FormState>();

    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 500),
        child: Container(
          margin: EdgeInsets.fromLTRB(50, 0, 50, 0),
          height: 500,
          child: Form(
            key: _formKey,
            child: Column(
              children: <Widget>[
                Container(
                  child: FittedBox(
                    fit: BoxFit.contain,
                    child: const FlutterLogo(),
                  ),
                  width: 175,
                  margin: EdgeInsets.fromLTRB(0, 0, 0, 50),
                ),
                Expanded(
                  child: TextFormField(
                    controller: serverController,
                    validator: (value) {
                      if (value.isEmpty) {
                        return 'Please enter server address';
                      }
                      return null;
                    },
                    decoration: InputDecoration(
                      labelText: 'Server Address'
                    ),
                  ),
                ),
                Expanded(
                  child: TextFormField(
                    controller: userController,
                    validator: (value) {
                      if (value.isEmpty) {
                        return 'Please enter username or email';
                      }
                      return null;
                    },
                    decoration: InputDecoration(
                      labelText: 'Username / Email'
                    ),
                  ),
                ),
                Expanded(
                  child: TextFormField(
                    obscureText: true,
                    enableSuggestions: false,
                    autocorrect: false,
                    controller: passwordController,
                    validator: (value) {
                      if (value.isEmpty) {
                        return 'Please enter password';
                      }
                      return null;
                    },
                    decoration: InputDecoration(
                      labelText: 'Password'
                    ),
                  ),
                ),
                SizedBox(
                  width: double.infinity,
                  child: PlatformButton(
                    onPressed: () {
                      if (!_formKey.currentState.validate()) 
                        return;
                      bloc.attemptLogin(userController.text, passwordController.text, serverController.text);
                    },
                    child: Text('Login')
                  ),
                ),

                StreamBuilder<bool>(
                  stream: bloc.loginResult,
                  builder: (context, snapshot) {
                    if (snapshot.data == null || snapshot.data == true)
                      return Container();

                    return Expanded(
                      child: Padding(
                        padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
                        child: Text(
                          "Login Failed",
                          style: TextStyle(color: Colors.red),
                        )
                      ),
                    );
                  }
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
