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

import '../provider/data.dart';
import 'game.dart';
import '../widgets/my_app_bar.dart';
import '../widgets/dialog_fetch_error.dart';
import '../utils/constants.dart';

class Home extends StatelessWidget {
  static const String id = 'home';

  @override
  Widget build(BuildContext context) {
    Orientation orientation = MediaQuery.of(context).orientation;
    Data _myProvider = Provider.of<Data>(context);

    List<Widget> _listWidgets() {
      return [
        Image.asset(
          'assets/images/icon128.png',
          scale: orientation == Orientation.portrait ? 1 : 1.5,
        ),
        Padding(
          padding: orientation == Orientation.portrait
              ? EdgeInsets.only(top: 10.0)
              : EdgeInsets.only(left: 10.0),
          child: Text(
            'Version: ${_myProvider.version}',
            textAlign: orientation == Orientation.portrait ? TextAlign.center : TextAlign.left,
          ),
        ),
      ];
    }

    void _errorWord(context) {
      showDialog(
        context: context,
        builder: (_) => AlertDialog(
          title: Text('Erreur inattendue'),
          content: Text('Erreur inattendue à la récupération d\'un mot aléatoire.\n'
              'Installer une nouvelle version de l\'application pourrait corriger cette anomalie.'),
          actions: <Widget>[
            FlatButton(
              child: Text('Fermer'),
              onPressed: () => Navigator.of(context).pop(),
            )
          ],
        ),
      );
    }

    return Scaffold(
      appBar: MyAppBar(appBar: AppBar()),
      body: Builder(
        builder: (context) => Center(
          child: _myProvider.searching == true
              ? WillPopScope(
                  onWillPop: () async => false,
                  child: Center(
                    child: CircularProgressIndicator(),
                    /*child: Text(
                      'Generando una palabra,\nespera un momento por favor...',
                      textAlign: TextAlign.center,
                    ),*/
                  ),
                )
              : Container(
                  child: SingleChildScrollView(
                    child: SizedBox(
                      height: MediaQuery.of(context).size.height / 1.25,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
                            child: FittedBox(
                              fit: BoxFit.fitWidth,
                              child: Text(
                                'LE PENDU',
                                style: TextStyle(
                                  fontFamily: 'Tiza',
                                  fontSize: 28.0,
                                  color: Colors.grey[700],
                                ),
                              ),
                            ),
                          ),
                          Container(
                            child: orientation == Orientation.portrait
                                ? Column(children: _listWidgets())
                                : Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: _listWidgets(),
                                  ),
                          ),
                          RaisedButton.icon(
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.all(Radius.circular(10.0))),
                            color: Color(board),
                            textColor: Colors.white,
                            padding: EdgeInsets.all(10.0),
                            onPressed: () async {
                              Scaffold.of(context).removeCurrentSnackBar();
                              _myProvider.resetGame();
                              _myProvider.searching = true;
                              bool control = true;
                              await Game().pickWord(context, _myProvider);
                              if (_myProvider.secretWord == null ||
                                  _myProvider.secretWord == '' ||
                                  _myProvider.hiddenWord == null ||
                                  (_myProvider.hiddenWord?.isEmpty ?? true)) {
                                control = false;
                                var response = await Navigator.push(
                                  context,
                                  MaterialPageRoute(builder: (context) => DialogFetchError()),
                                );
                                if (response == false) {
                                  _myProvider.searching = false;
                                  _myProvider.resetGame();
                                } else {
                                  _myProvider.setPrefGameMode = false;
                                  _myProvider.setPrefLevel = defaultLevel;
                                  await Game().pickWord(context, _myProvider);
                                  control = true;
                                }
                              }

                              if (_myProvider.secretWord == 'UNEXPECTED ERROR') {
                                control = false;
                                _myProvider.resetGame();
                                _errorWord(context);
                              }

                              if (control) {
                                Navigator.pushNamed(context, Game.id)
                                    .then((value) => _myProvider.searching = false);
                              }
                            },
                            icon: Icon(
                              Icons.check_box,
                              color: Colors.white,
                              size: 60.0,
                            ),
                            label: Column(
                              children: [
                                Text(
                                  'JOUER',
                                  style: TextStyle(
                                    fontSize: 22.0,
                                    letterSpacing: 2.0,
                                  ),
                                ),
                                Text(
                                  'Mode de jeu: ${_myProvider.levelPref}',
                                  style: TextStyle(
                                    fontSize: 10.0,
                                    fontWeight: FontWeight.w300,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
        ),
      ),
    );
  }
}