import 'package:app_hit_a_wod/src/blocs/stats.bloc.dart';
import 'package:app_hit_a_wod/src/models/bi_exercises.model.dart';
import 'package:app_hit_a_wod/src/models/bi_training_session.model.dart';
import 'package:app_hit_a_wod/src/models/exercise.model.dart';
import 'package:app_hit_a_wod/src/models/subscription_selection.model.dart';
import 'package:app_hit_a_wod/src/models/training_workout.model.dart';
import 'package:app_hit_a_wod/src/models/user.model.dart';
import 'package:app_hit_a_wod/src/providers/auth.provider.dart';
import 'package:app_hit_a_wod/src/providers/user-subscriptions.provider.dart';
import 'package:app_hit_a_wod/src/styles.dart';
import 'package:app_hit_a_wod/src/utils/custom_datepicker/datepicker_neu.dart';
import 'package:app_hit_a_wod/src/utils/custom_training_session_action_button.dart/training_session_action_button.dart';
import 'package:app_hit_a_wod/src/utils/fontello/my_flutter_app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';

class StatsPage extends StatefulWidget {
  const StatsPage({Key key}) : super(key: key);

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

class _StatsPageState extends State<StatsPage> {
  String nameWorkout = null;
  String categoryWorkout = "Todos";
  String nameExercise = null;
  String lvlExercise = "Todos";
  final lvls = {
    "Todos" : null,
    "Fácil" : 1,
    "Medio" : 2,
    "Difícil": 3
  };
  @override
  Widget build(BuildContext context) {
    final AuthProvider auth = Provider.of<AuthProvider>(context);
    final UserSubscriptionsProvider us_provider = Provider.of<UserSubscriptionsProvider>(context);
    final StatsBloc bloc = StatsBloc(
      context: context, 
      user_id: auth.currentUser.id,
      box_id: us_provider.currentActiveSubscription.box.id, 
    );

    return StreamBuilder(
      stream: bloc.selectedPageStream,
      builder: (context, snapshot) {
        return Container(
          padding: EdgeInsets.only(top: 20.0, left: 20.0, right: 20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              StreamBuilder(
                stream: CombineLatestStream.combine3(auth.userStream, us_provider.activeStream, bloc.showFiltersStream, (user, ss, bool showFilters) => {"user": user, "ss": ss, "showFilters": showFilters}),
                builder: (BuildContext context, AsyncSnapshot<dynamic> data) {
                  return _headerFilters(bloc,auth.currentUser.id,us_provider.currentActiveSubscription.box.id);
                }
              ),
              Expanded(
                child: (bloc.selectedPageValue==0) ? 
                  RefreshIndicator(
                    onRefresh: () async {
                      List<Future> list = [];
                      list.add(bloc.refreshTrainingSessions(auth.currentUser.id,us_provider.currentActiveSubscription.box.id));
                      await Future.wait(list);
                      return;
                    },
                    color: colors["primary"],
                    displacement: 1,
                    child: Stack(
                      children: <Widget>[
                        StreamBuilder(
                          stream: CombineLatestStream.combine3(auth.userStream, us_provider.activeStream, bloc.trainingSessionStream, (user, ss, List<BITrainingSession> trainingSessions) => {"user": user, "ss": ss, "trainingSessions": trainingSessions}),
                          builder: (BuildContext context, AsyncSnapshot<dynamic> data) {
                            if(data.connectionState == ConnectionState.active && data.hasData) {
                              final User user = data.data["user"];
                              final SubscriptionSelection ss = data.data["ss"];
                              final List<BITrainingSession> trainingSessions = data.data["trainingSessions"];
                              if(trainingSessions!=null && trainingSessions.length>0){
                                
                                return ListView.builder(
                                  shrinkWrap: true,
                                  itemCount: trainingSessions.length,
                                  itemBuilder: (BuildContext context, int index) {
                                    return Container(
                                      child: _generateTrainingSessionCard(context,trainingSessions[index],index,user, 
                                        neuTrainingSessionActionButton(
                                          ts: trainingSessions[index],
                                          onClicked: (newTs){
                                            if (this.mounted) {
                                              setState(() {
                                                trainingSessions[index] = newTs;
                                              });
                                            }
                                          },)
                                        ),
                                      padding: EdgeInsets.only(bottom: 20.0),
                                    );
                                  }
                                );
                              } else  if (trainingSessions==null) {
                                return _neuCargando();
                              } else {
                                return SingleChildScrollView(
                                  child: neuContainer(
                                    Column(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
                                      shaderContainer(Icon(MyFlutterApp.depressed, size: 80,), 'letter', [colors["primary"], colors["secondary"]]),
                                      SizedBox(height: 50),
                                      Text("Vaya, no parece que haya resultados", style: Theme.of(context).textTheme.body1)
                                    ]),
                                    width: double.infinity,
                                    height: 250
                                  )
                                );
                              }                          
                            } else {
                              return _neuCargando();
                            }
                          }
                        )
                      ]
                    )
                  )
                  : (bloc.selectedPageValue==1) ?
                  RefreshIndicator(
                    onRefresh: () async {
                      List<Future> list = [];
                      list.add(bloc.refreshExercises(auth.currentUser.id,us_provider.currentActiveSubscription.box.id,this.nameExercise));
                      await Future.wait(list);
                      return;
                    },
                    color: colors["primary"],
                    displacement: 1,
                    child: Stack(
                      children: <Widget>[
                        StreamBuilder(
                          stream: CombineLatestStream.combine3(auth.userStream, us_provider.activeStream, bloc.exercisesStrem, (user, ss, List<Exercise> exercises) => {"user": user, "ss": ss, "exercises": exercises}),
                          builder: (BuildContext context, AsyncSnapshot<dynamic> data) {
                            if(data.connectionState == ConnectionState.active && data.hasData) {
                              final User user = data.data["user"];
                              final SubscriptionSelection ss = data.data["ss"];
                              final List<Exercise> exercises = data.data["exercises"];
                              if(exercises!=null && exercises.length>0){
                                return ListView.builder(
                                  shrinkWrap: true,
                                  itemCount: exercises.length,
                                  itemBuilder: (BuildContext context, int index) {
                                    return Container(
                                      child: _generateExerciseCard(context,exercises[index],user),
                                      padding: EdgeInsets.only(bottom: 20.0),
                                    );
                                  }
                                );
                              } else  if (exercises==null) {
                                return _neuCargando();
                              } else {
                                return SingleChildScrollView(
                                  child: neuContainer(
                                    Column(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
                                      shaderContainer(Icon(MyFlutterApp.depressed, size: 80,), 'letter', [colors["primary"], colors["secondary"]]),
                                      SizedBox(height: 50),
                                      Text("Vaya, no parece que hay puntuaciones de ningun ejercicio", style: Theme.of(context).textTheme.body1)
                                    ]),
                                    width: double.infinity,
                                    height: 250
                                  )
                                );
                              }                          
                            } else {
                              return _neuCargando();
                            }
                          }
                        )
                      ]
                    )
                  ) : 
                  RefreshIndicator(
                    onRefresh: () async {
                      List<Future> list = [];
                      list.add(bloc.refreshWorkouts(auth.currentUser.id,this.nameWorkout));
                      await Future.wait(list);
                      return;
                    },
                    color: colors["primary"],
                    displacement: 1,
                    child: Stack(
                      children: <Widget>[
                        StreamBuilder(
                          stream: CombineLatestStream.combine3(auth.userStream, us_provider.activeStream, bloc.workoutsStrem, (user, ss, List<TrainingWorkout> workouts) => {"user": user, "ss": ss, "workouts": workouts}),
                          builder: (BuildContext context, AsyncSnapshot<dynamic> data) {
                            if(data.connectionState == ConnectionState.active && data.hasData) {
                              final User user = data.data["user"];
                              final SubscriptionSelection ss = data.data["ss"];
                              final List<TrainingWorkout> workouts = data.data["workouts"];
                              if(workouts!=null && workouts.length>0){
                                return ListView.builder(
                                  shrinkWrap: true,
                                  itemCount: workouts.length,
                                  itemBuilder: (BuildContext context, int index) {
                                    return Container(
                                      child: getMiniWorkout(context, workouts[index]),
                                      padding: EdgeInsets.only(bottom: 20.0),
                                    );
                                  }
                                );
                                /* return Container(
                                  width: double.infinity,
                                  child: Wrap(
                                    runSpacing: 20.0,
                                    children: workout_cards
                                  ),
                                ); */
                              } else  if (workouts==null) {
                                return _neuCargando();
                              } else {
                                return SingleChildScrollView(
                                  child: neuContainer(
                                    Column(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
                                      shaderContainer(Icon(MyFlutterApp.depressed, size: 80,), 'letter', [colors["primary"], colors["secondary"]]),
                                      SizedBox(height: 50),
                                      Text("Vaya, no parece que haya ningun entreno", style: Theme.of(context).textTheme.body1)
                                    ]),
                                    width: double.infinity,
                                    height: 250
                                  )
                                );
                              }                          
                            } else {
                              return _neuCargando();
                            }
                          }
                        )
                      ]
                    )
                  )
              )
            ],
          ),
        );
      }
    );
  }

  Widget _generateExerciseCard(BuildContext context, Exercise e, User user,) {
    final level = ['Fácil','Medio','Difícil'];
    return neuContainer(
      InkWell(
        child: Wrap(
          runSpacing: 20.0,
          spacing: 20.0,
          crossAxisAlignment: WrapCrossAlignment.center,
          alignment: WrapAlignment.spaceBetween,
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                  child: Container(
                    child: Text('${e.name}', style: Theme.of(context).textTheme.title.copyWith(fontSize: 18.0),)
                  ),
                ),
                neuChip(
                  Text('${level[e.level-1]}',style: TextStyle(color: Colors.white),),
                  colors: colors_list[colors_level[e.level.toString()]]
                ),
              ],
            ),
            Container(
              width: double.infinity,
              child: Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                alignment: WrapAlignment.start,
                runSpacing: 10.0,
                children: <Widget>[
                  e.type!=null ? Container(
                    child: neuChip(
                      Text('${e.type}',style: TextStyle(color: Colors.white),)
                    ),
                  ) : SizedBox(),
                  e.type!=null ? SizedBox(height: 20.0, width: 5.0,) : SizedBox(),
                  Container(
                    child: neuChip(
                      Container(
                        child: Wrap(
                          children: <Widget>[
                            Icon(MyFlutterApp.kettlebell, size: 14.0, color: Colors.white,),
                            Text("${(e.equipment_type!=null) ? ' '+e.equipment_type : ' Sin equipamiento'}", style: TextStyle(color: Colors.white),)
                          ],
                        ),
                      ),
                      colors: colors_list['secondary']
                    )
                  )
                ],
              ),
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: Text("${e.description!=null && !e.description.isEmpty ? e.description : 'No hay descripción para este ejercicio'}", overflow: TextOverflow.ellipsis, maxLines: 2, style: Theme.of(context).textTheme.body1.copyWith(fontSize: 15.0),),
                )
              ],
            ),
            Container(
              width: double.infinity,
              child: Row(
                children: <Widget>[
                  Expanded(child: SizedBox(),),
                  neuButton (
                    NeumorphicButton(
                      boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(30)),
                      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
                      style: NeumorphicStyle(
                        color: Colors.transparent,
                        depth: neuDepth,
                      ),
                      child: Wrap(
                        crossAxisAlignment: WrapCrossAlignment.center,
                        children: <Widget>[
                          Text("Ver ejercicio", style: TextStyle(color: colors['primary']),),
                          Icon(MyFlutterApp.right_arrow, color: colors['primary'],size: 15.0)
                        ],
                        spacing: 5,
                        runSpacing: 5,
                        alignment: WrapAlignment.center
                      ),
                      onClick: () {
                        Navigator.pushNamed(context, 'exercise-detail', arguments: e);
                      },
                    ),
                  )
                ],
              )
            ),
          ],
        ),
        onTap: () {

        },
      )
    );
  }

  Widget _generateTrainingSessionCard(BuildContext context, BITrainingSession ts, int index, User user, Widget button) {
    return neuContainer(
      InkWell(
        child: Wrap(
          runSpacing: 10.0,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                ts.training_type.name!=null ? neuChip(
                  Text('${ts.training_type.name}',style: TextStyle(color: Colors.white),),
                  colors: colors_list[colors_type[ts.training_type.slug]]
                ) : SizedBox(),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    Container(
                      height: 15.0,
                      alignment: Alignment.centerRight,
                      child: Text('${DateFormat('dd/MM/yyyy').format(ts.date_start.toLocal())}', style: Theme.of(context).textTheme.subtitle.copyWith(fontWeight: FontWeight.w500))
                    ),
                    SizedBox(height: 5.0),
                    Container(
                      height: 15.0,
                      alignment: Alignment.centerRight,
                      child: Text('${DateFormat('kk:mm').format(ts.date_start.toLocal())} - ${DateFormat('kk:mm').format(ts.date_end.toLocal())}', style: Theme.of(context).textTheme.subtitle.copyWith(fontWeight: FontWeight.w400))
                    ),
                  ],
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Expanded(
                  child: Container(
                    width: MediaQuery.of(context).size.width * 0.5 - 40.0,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          child: Text('Sala principal', style: Theme.of(context).textTheme.subtitle),
                        ),
                        SizedBox(height: 5.0,),
                        Container(
                          child: Text('Capacidad: ${ts.capacity!=null ? ts.capacity : '∞'}', style: Theme.of(context).textTheme.body1),
                        )
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    width: MediaQuery.of(context).size.width * 0.5 - 40.0,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          alignment: Alignment.centerRight,
                          width: double.infinity,
                          child: _getParticipants(context,ts.users,user)                  
                        ),
                      ],
                    ),
                  ),
                )
              ]
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Expanded(
                  child: _getCoach(context,ts.coach),
                ),
                Expanded(
                  child: button
                )
              ],
            )
            
          ],
        ),
        onTap: () {
          Navigator.pushNamed(context, 'training-session-detail', arguments: {"trainingSession": ts, "day": ts.date_start});
        },
      )
    );
  }

  _getCoach(BuildContext context,User coach) {
    return (coach!=null) ?
      Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('Coach', style: Theme.of(context).textTheme.subtitle),
            SizedBox(height: 5.0,),
            Row(
              children: <Widget>[
                neuProfilePhoto(context,coach),
                SizedBox(width: 5.0,),
                Container(
                  width: MediaQuery.of(context).size.width * 0.5 - 110.0,
                  child: Text('${coach.name + ' ' + coach.surnames}', style: Theme.of(context).textTheme.body1, overflow: TextOverflow.fade,),
                )
              ],
            )
          ],
        ),
      )
    :
      SizedBox(height: 0.0,width: 0.0,);
  }

  _getParticipants(BuildContext context, List<User> users, User user) {
    final user_size = users.length>=3 ? 3 : users.length;
    users = _orderParticipants(users,user,user_size-1);
    return (users!= null && users.length>0) ? 
      Align(
        alignment: Alignment.centerRight,
        child: Container(          
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Stack(
                alignment: Alignment.centerRight,
                children: new List.generate(user_size, (i) => _getImageParticipant(context, users[i],i,user_size,user)),
              ),
              ( users.length!=user_size && users.length>0 ) ? Text(" + ${users.length - user_size}", style: Theme.of(context).textTheme.body1,) : Text('')
            ],
          ),
        ),
      )
    :
      Text('0');
  }

  _orderParticipants(List<User> users, User currentUser, int user_pos) {
    var me = users.firstWhere((u) => u.id == currentUser.id, orElse: () => null);
    if(me!=null) {
      users.removeWhere((element) => element.id == currentUser.id);
      users.insert(user_pos, me);
    }
    return users;
  }

  _getImageParticipant(BuildContext context, User user, int index, int user_size, User currentUser) {
    return neuProfilePhoto(context,user,margin: EdgeInsets.only(right:(30.0*(user_size-(index+1)))),user_id: currentUser.id );
  }

  Widget _neuCargando() {
    return Container(
      width: double.infinity,
      child: Wrap(
        runSpacing: 20.0,
        children: <Widget>[
          neuSkeletonCard(200, double.infinity),
          neuSkeletonCard(200, double.infinity),
          neuSkeletonCard(200, double.infinity)
        ]
      ),
    );
  }

  Widget _selectorDePagina(StatsBloc bloc, int user_id, int box_id) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 20.0),
      child: Row(
        children: <Widget>[
          _containerExpanded((bloc.selectedPageValue==0),NeumorphicButton(
            padding: EdgeInsets.all(20),
            style: (bloc.selectedPageValue==0) ? neuStylePressed() : neuButtonStyle(),
            boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(50)),
            child: (bloc.selectedPageValue==0) ? 
            Container(
              alignment: Alignment.center,
              child: Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                alignment: WrapAlignment.center,
                spacing: 10.0,
                runSpacing: 5.0,
                children: <Widget>[
                  Icon(MyFlutterApp.calendar_check_o, size: 18.0, color: colors['primary']),
                  Text("Últimas sesiones", style: TextStyle(color: colors['primary'])),
                ],
              ),
            ) : 
            Container(child: Icon(MyFlutterApp.calendar_check_o, size: 18.0, color: Color(0xFF575F6B))),
            onClick: () {
              bloc.selectedPageSet(0);
            },
          )),
          SizedBox(width: 15.0,),
          _containerExpanded((bloc.selectedPageValue==1),NeumorphicButton(
            padding: EdgeInsets.all(20),
            style: (bloc.selectedPageValue==1) ? neuStylePressed() : neuButtonStyle(),
            boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(50)),
            child: (bloc.selectedPageValue==1) ? 
            Container(
              alignment: Alignment.center,
              child: Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                alignment: WrapAlignment.center,
                spacing: 10.0,
                runSpacing: 5.0,
                children: <Widget>[
                  Icon(MyFlutterApp.kettlebell, size: 18.0,color: colors['primary']),
                  Text("Ejercicios", style: TextStyle(color: colors['primary']),),
                ],
              ),
            ) : 
            Container(child: Icon(MyFlutterApp.kettlebell, size: 18.0, color: Color(0xFF575F6B),),),
            onClick: () {
              bloc.selectPage(1, user_id, box_id);
            },
          )),
          SizedBox(width: 15.0,),
          _containerExpanded((bloc.selectedPageValue==2),NeumorphicButton(
            padding: EdgeInsets.all(20),
            style: (bloc.selectedPageValue==2) ? neuStylePressed() : neuButtonStyle(),
            boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(50)),
            child: (bloc.selectedPageValue==2) ? 
            Container(
              alignment: Alignment.center,
              child: Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                alignment: WrapAlignment.center,
                spacing: 10.0,
                runSpacing: 5.0,
                children: <Widget>[
                  Icon(MyFlutterApp.stopwatch, size: 18.0,color: colors['primary']),
                  Text("Workouts", style: TextStyle(color: colors['primary']),),
                ],
              ),
            ) : 
            Container(child: Icon(MyFlutterApp.stopwatch, size: 18.0, color: Color(0xFF575F6B),)),
            onClick: () {
              bloc.selectPage(2, user_id, box_id);
            },
          )),
        ],
      ),
    );
  }

  _containerExpanded(bool condition, Widget child) {
    if ( condition ) {
      return Expanded(
        child: child,
      );
    } else {
      return Container(
        child: child,
      );
    }
  }

  _headerFilters(StatsBloc bloc, int user_id, int box_id) {
    return Container(
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              neuButton (
                StreamBuilder(
                  stream: bloc.dirStream,
                  builder: (context, snapshot) {
                    return NeumorphicButton(
                      padding: EdgeInsets.all(12),
                      style: neuButtonStyle(),
                      boxShape: neuBoxShape(),
                      child: Icon((bloc.dirValue=='asc') ? MyFlutterApp.down_arrow : MyFlutterApp.up_arrow, size: 18.0, color: Color(0xFF575F6B),),
                      onClick: () {
                        if (bloc.dirValue=='asc') bloc.dirSet('desc');
                        else bloc.dirSet('asc');
                        bloc.refreshExercises(user_id, box_id, this.nameExercise);
                        bloc.refreshTrainingSessions(user_id, box_id);
                        bloc.refreshWorkouts(user_id, this.nameWorkout);
                      },
                    );
                  }
                ),
              ),
              Expanded(
                child: Column(
                  children: <Widget>[
                    Container(
                      alignment: Alignment.center,
                      child: Text("Tus resultados", style: Theme.of(context).textTheme.subtitle,)
                    )
                  ],
                ),
              ),
              neuButton (
                NeumorphicButton(
                  padding: EdgeInsets.all(10),
                  style: neuButtonStyle(),
                  boxShape: neuBoxShape(),
                  child: Icon(Icons.search, color: bloc.showFiltersValue ? colors['primary'] : Color(0xFF575F6B)),
                  onClick: () {
                    this.nameExercise = null;
                    this.nameWorkout = null;
                    bloc.changeShowFilters(user_id,box_id);
                  },
                ),
              )
            ],
          ),
          _selectorDePagina(bloc, user_id, box_id),
          (bloc.showFiltersValue) ? _filtres(bloc, user_id, box_id) : SizedBox()
        ],
      ),
    );
  }

  _filtres(StatsBloc bloc, int user_id, int box_id) {
    return (bloc.selectedPageValue==0) ? 
      _filtresData(bloc, user_id, box_id)
      :
      (bloc.selectedPageValue==1) ? 
        _filtersExercises(bloc, user_id, box_id)
        :
        _filtersWorkouts(bloc, user_id, box_id);
  }

  _filtresData(StatsBloc bloc, int user_id, int box_id) {
    return StreamBuilder<Object>(
      stream: CombineLatestStream.combine2(bloc.dataIniStream, bloc.dataFiStream, (a, b) => {"ini": a, "fi": b}),
      builder: (context, snapshot) {
        return Container(
          padding: EdgeInsets.only(bottom: 20.0),
          width: double.infinity,
          child: Row(
              children: <Widget>[
                Expanded(
                  child: Column(
                    children: <Widget>[
                      Text("Fecha de inicio"),
                      SizedBox(height: 10.0),
                      Container(
                        width: double.infinity,
                        child: neuDatePicker(
                          NeumorphicButton(
                            style: neuStylePressed(),
                            boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(neuRounded)),
                            padding: EdgeInsets.all(20), 
                            child: Container(
                              color: Colors.transparent,
                              child: Text(bloc.dataIniValue!=null ? DateFormat('dd/MM/yyyy').format(bloc.dataIniValue) : '--/--/----'),
                            ),
                            onClick: () {
                              _selectDate(context, "ini", bloc, user_id, box_id);
                            }
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(width: 20.0,),
                Expanded(
                  child: Column(
                    children: <Widget>[
                      Text("Fecha final"),
                      SizedBox(height: 10.0),
                      Container(
                        width: double.infinity,
                        child: neuDatePicker(
                          NeumorphicButton(
                            style: neuStylePressed(),
                            boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(neuRounded)),
                            padding: EdgeInsets.all(20), 
                            child: Container(
                              color: Colors.transparent,
                              child: Text(bloc.dataFiValue!=null ? DateFormat('dd/MM/yyyy').format(bloc.dataFiValue) : '--/--/----'),
                            ),
                            onClick: () {
                              _selectDate(context, "fi", bloc, user_id, box_id);
                            }
                          ),
                        ),
                      ),
                    ],
                  ),
                )
              ]
          )
        );
      }
    );
  }

  Future<Null> _selectDate(BuildContext context, String data, StatsBloc bloc, int user_id, int box_id) async {
    final DateTime picked = await showNeuDatePicker(
      context: context,
      initialDate: (data=="ini") ? (bloc.dataIniValue!=null ? bloc.dataIniValue : DateTime.now()) : (bloc.dataFiValue!=null ? bloc.dataFiValue : DateTime.now()),
      firstDate: DateTime(2015),
      lastDate: DateTime(2101)
    );
    if (picked != null && picked != (data=="ini" ? bloc.dataIniValue : bloc.dataFiValue)) {
      if (data=="ini") bloc.dataIniSet(picked);
      else bloc.dataFiSet(picked);
      bloc.refreshTrainingSessions(user_id, box_id,);
    }
  }

  _filtersExercises(StatsBloc bloc, int user_id, int box_id) {
    return Container(
      padding: EdgeInsets.only(bottom: 20.0),
      width: double.infinity,
      child: Row(
        children: <Widget>[
          Expanded(
            child: neuInput(
              Container(
                width: double.infinity,
                height: 50,
                child: TextFormField(
                  keyboardType: TextInputType.text,
                  decoration: InputDecoration(
                    contentPadding: EdgeInsets.symmetric(vertical: 20, horizontal: 5),
                    border: InputBorder.none,
                    hintText: 'Nombre del ejercicio',
                    errorStyle: TextStyle(color: colors["seven"])
                  ),
                  onChanged: (val) {
                    this.nameExercise = val.length>0 ? val : null;
                    if(this.nameExercise==null) bloc.refreshExercises(user_id, box_id, this.nameExercise);
                    else if (this.nameExercise.length>=3) bloc.refreshExercises(user_id,box_id, this.nameExercise);
                  },
                ),
              )
            ),
          ),
          SizedBox(width: 20.0,),
          neuButton (
            NeumorphicButton(
              padding: EdgeInsets.all(10),
              style: neuButtonStyle(),
              boxShape: neuBoxShape(),
              child: Icon(Icons.add, color: bloc.showFiltersValue ? colors['primary'] : Colors.black),
              onClick: () {
                Navigator.pushNamed(context, 'exercise-filter', arguments: {"name": this.nameExercise, "dir": bloc.dirValue});
              },
            ),
          )
        ],
      ),
    );
  }

  _filtersWorkouts(StatsBloc bloc, int user_id, int box_id) {
    return Container(
      padding: EdgeInsets.only(bottom: 20.0),
      width: double.infinity,
      child: Row(
        children: <Widget>[
          Expanded(
            child: neuInput(
              Container(
                height: 50,
                child: TextFormField(
                  keyboardType: TextInputType.text,
                  decoration: InputDecoration(
                    contentPadding: EdgeInsets.symmetric(vertical: 20, horizontal: 5),
                    border: InputBorder.none,
                    hintText: 'Nombre del Workout',
                    errorStyle: TextStyle(color: colors["seven"])
                  ),
                  onChanged: (val) {
                    this.nameWorkout = val.length>0 ? val : null;
                    if(this.nameWorkout==null) bloc.refreshWorkouts(user_id, this.nameWorkout);
                    else if (this.nameWorkout.length>=3) bloc.refreshWorkouts(user_id, this.nameWorkout);                      
                  },
                ),
              )
            )
          ),
          SizedBox(width: 20.0,),
          neuButton (
            NeumorphicButton(
              padding: EdgeInsets.all(10),
              style: neuButtonStyle(),
              boxShape: neuBoxShape(),
              child: Icon(Icons.add, color: bloc.showFiltersValue ? colors['primary'] : Colors.black),
              onClick: () {
                Navigator.pushNamed(context, 'training-workout-filter', arguments: {"name": this.nameWorkout, "dir": bloc.dirValue});
              },
            ),
          )
        ],
      ),
    );
  }

}