import 'dart:io';

import 'package:app_hit_a_wod/src/blocs/dashboard.bloc.dart';
import 'package:app_hit_a_wod/src/models/bi_training_session.model.dart';
import 'package:app_hit_a_wod/src/models/new.model.dart';
import 'package:app_hit_a_wod/src/models/subscription_selection.model.dart';
import 'package:app_hit_a_wod/src/models/training_session.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/models/user_benchmark.model.dart';
import 'package:app_hit_a_wod/src/models/user_benchmark_section.model.dart';
import 'package:app_hit_a_wod/src/pages/my_orders/my_order_detail.page.dart';
import 'package:app_hit_a_wod/src/pages/user/user.page.dart';
import 'package:app_hit_a_wod/src/providers/api.provider.dart';
import 'package:app_hit_a_wod/src/providers/auth.provider.dart';
import 'package:app_hit_a_wod/src/providers/main_scaffold.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_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:cached_network_image/cached_network_image.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:url_launcher/url_launcher.dart';

class InitialPage extends StatefulWidget {

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

class _InitialPageState extends State<InitialPage> {
  @override
  Widget build(BuildContext context) {

    final us_provider = Provider.of<UserSubscriptionsProvider>(context);
    final api = Provider.of<ApiProvider>(context);
    final auth = Provider.of<AuthProvider>(context);
    return SingleChildScrollView(
      padding: EdgeInsets.all(20),
      child: StreamBuilder(
        stream: us_provider.activeStream,
        builder: (context, data) {
          if (data.hasData) {
            final SubscriptionSelection ss = data.data;
            final bloc = DashboardBloc(context: context, user_id: auth.currentUser.id, box_id: us_provider.currentActiveSubscription.box.id, subscription_selection_id: ss.us.id);
            return Container(
              color: Colors.transparent,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _homeSubscriptionSelector(context, ss, us_provider),
                  SizedBox(height: 20),
                  _circleGraphs(context, ss),
                  SizedBox(height: 20),
                  StreamBuilder(
                    stream: bloc.dashboardStream,
                    builder: (context, data) {
                      if(data.hasData) {
                        final int status = data.data["status"];
                        final New last_new = data.data["last_new"];
                        final Map<String, dynamic> last_session_benchmark = data.data["last_session_benchmark"];
                        final BITrainingSession next_training_session = data.data["next_training_session"];
                        final bool should_train_more = data.data["should_train_more"];
                        final List<User> birthdays = data.data["birthdays"];
                        return Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            _userSubscriptionStatus(context, status, ss), //inclou espai a sota
                            _lastBoxNew(context, last_new, ss), //inclou espai a sota
                            _lastSessionBenchmark(context, last_session_benchmark, ss, auth),  //inclou espai a sota
                            _nextTrainingSession(context, next_training_session, auth), //inclou espai a sota
                            _shouldTrainMoreCard(context, should_train_more, ss), //inclou espai a sota
                            _happyBirthday(context, birthdays, ss),
                          ]
                        );
                      }
                      else return _fullSkeleton();
                    }
                  ),
                  _aboutMyBox(context, ss)
                ]
              )
            );
          }
          else return _fullSkeleton();
        }
        
      ),
    );
  }

  _homeSubscriptionSelector(BuildContext context, SubscriptionSelection ss, UserSubscriptionsProvider us_provider) {
    return neuButton(NeumorphicButton(
      padding: EdgeInsets.all(20),
      style: neuButtonStyle(),
      child: Row(children: <Widget>[
        ClipRRect(borderRadius: BorderRadius.circular(8), child: CachedNetworkImage(imageUrl: ss.company.logo_url, placeholder: (_, __) => neuSkeletonCard(55, 55), width: 55, height: 55, fit: BoxFit.cover,)),
        SizedBox(width: 20),
        Expanded(
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
            Text("${ss.company.name}, ${ss.box.city}", style: Theme.of(context).textTheme.body1.copyWith(fontWeight: FontWeight.w500), overflow: TextOverflow.clip),
            SizedBox(height: 10),
            Text(ss.role.name, style: Theme.of(context).textTheme.body1, overflow: TextOverflow.clip)
          ]),
        )
      ]),
      onClick: () {
        us_provider.openSubscriptionsDialog();
      }
    ));
  }

  _circleGraphs(BuildContext context, SubscriptionSelection ss) {
    return Column(
      children: <Widget>[
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            UserPage.circleGraph(context, number: ss.us.wod_counter, max: ss.pricing.wod_counter, detail: "WODs"),
            Expanded(child: SizedBox()),
            UserPage.circleGraph(context, number: ss.us.open_counter, max: ss.pricing.open_counter, detail: "Open"),
            Expanded(child: SizedBox()),
            UserPage.circleGraph(context, number: ss.us.total_counter, max: ss.pricing.total_counter, detail: "Totales")
          ]
        ),
        SizedBox(height: 20),
      ],
    );  
  }

  _fullSkeleton() {
    return Column(children: <Widget>[
      neuSkeletonCard(150, double.infinity),
      SizedBox(height: 20),
      neuSkeletonCard(150, double.infinity),
      SizedBox(height: 20),
      neuSkeletonCard(150, double.infinity),
      SizedBox(height: 20),
      neuSkeletonCard(150, double.infinity),
      SizedBox(height: 20),
      neuSkeletonCard(150, double.infinity),
      SizedBox(height: 20),
      neuSkeletonCard(150, double.infinity)
    ]);
  }

  _userSubscriptionStatus(BuildContext context, int status, SubscriptionSelection ss) {
    if(status==3) { //a punt de caducar
      if(ss.us.renew && ss.us.stripe_id!=null) {
        return Column(children: <Widget>[
          _userSubscriptionStatusCard(context, "Renovación de suscripción", "Tu suscripción será renovada el próximo ${DateFormat('dd/MM/yyyy').format(ss.us.end_date)} de forma automática.", status: "normal"),
          SizedBox(height: 20)
        ]);
      }
      else {
        return Column(children: <Widget>[
          _userSubscriptionStatusCard(context, "¡Está a punto de caducar!", "Tu suscripción caducará el próximo ${DateFormat('dd/MM/yyyy').format(ss.us.end_date)}, acuérdate de renovarla.", status: "warning"),
          SizedBox(height: 20)
        ]);
      }
    }
    else if(status==4) { //en prorroga
        return Column(children: <Widget>[
          _userSubscriptionStatusCard(context, "¡Estás en prórroga!", "Tu suscripción ha entrado en período de prórroga de forma temporal. En las próximas horas perderás acceso a la aplicación si no renuevas.", status: "error"),
          SizedBox(height: 20)
        ]);
    }
    else if(status==5) { //inactiva
        return Column(children: <Widget>[
          _userSubscriptionStatusCard(context, "Suscripción caducada", "Tu suscripción ha sido desactivada. Dirígete a tu box si quieres volver a activarla.", status: "error"),
          SizedBox(height: 20)
        ]);
    }
    else return Container();
  }

  _userSubscriptionStatusCard(BuildContext context, String title, String description, { String status = "normal" }) {
    final scaffold = Provider.of<MainScaffoldProvider>(context);
    return neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(title, style: Theme.of(context).textTheme.title, overflow: TextOverflow.clip),
          Row(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
            MaterialButton(
              minWidth: 0,
              onPressed: () {},
              elevation: 2,
              color: status=="warning" ? Colors.orange : (status=="error" ? colors["seven"] : colors["secondary"]),
              child: Icon((status=="warning" ? Icons.warning : (status=="error" ? Icons.error : Icons.info)), size: 20.0, color: colors["white"]),
              padding: EdgeInsets.all(18.0),
              shape: CircleBorder(),
            ),
            SizedBox(width: 20),
            Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
              Text(description, style: Theme.of(context).textTheme.body1, overflow: TextOverflow.clip),
              (
                status!="normal" ?
                Column(children: <Widget>[
                  SizedBox(height: 15),
                  Row(children: <Widget>[Expanded(child: SizedBox(),), neuButton(NeumorphicButton(
                    padding: EdgeInsets.all(20),
                    style: neuButtonStyle(),
                    child: Row(children: <Widget>[
                      Text("Renovar suscripción", style: Theme.of(context).textTheme.body1.copyWith(fontWeight: FontWeight.w500, color: status=="error" ? colors["seven"] : (status=="warning" ? Colors.orange : colors["secondary"]))),
                      SizedBox(width: 15),
                      Icon(Icons.arrow_forward_ios, size: 15, color: status=="error" ? colors["seven"] : (status=="warning" ? Colors.orange : colors["secondary"]))
                    ]),
                    boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(30)),
                    onClick: () {
                      scaffold.setPage(3);
                    },
                  ), borderRadius: BorderRadius.circular(30))])
                ]) :
                Container()
              )
            ]))
          ]),
        ],
      ),
      padding: EdgeInsets.all(20),
      width: double.infinity
    );
  }

  _lastBoxNew(BuildContext context, New n, SubscriptionSelection ss) {
    if(n==null || n.id==null) return Container();
    else return Column(
      children: <Widget>[
        neuContainer(Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
          Text("Última noticia del box", style: Theme.of(context).textTheme.title),
          SizedBox(height: 20),
          Row(mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
            Column(mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
              ClipRRect(borderRadius: BorderRadius.circular(8), child: CachedNetworkImage(imageUrl: ss.company.logo_url, placeholder: (_, __) => neuSkeletonCard(55, 55), width: 55, height: 55, fit: BoxFit.cover,)),
              SizedBox(height: 10),
              Text(DateFormat('dd/MM/yy\nHH:mm').format(n.created_at), style: Theme.of(context).textTheme.body1.copyWith(fontStyle: FontStyle.italic, fontSize: 14), textAlign: TextAlign.center,)
            ]),
            SizedBox(width: 20),
            Expanded(child: Column(mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
              Text(n.title, style: Theme.of(context).textTheme.body1.copyWith(fontWeight: FontWeight.w500), overflow: TextOverflow.clip,),
              SizedBox(height: 10),
              Text(n.description.length > 150 ? n.description.substring(0, 150) + '...' : n.description, style: Theme.of(context).textTheme.body1, overflow: TextOverflow.clip,),
            ]))
          ]),
          SizedBox(height: 20),
          Row(mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
            neuButton(NeumorphicButton(
              padding: EdgeInsets.all(20),
              style: neuButtonStyle(),
              child: Row(children: <Widget>[
                Text("Leer noticia", style: Theme.of(context).textTheme.body1.copyWith(color: colors["white"]), textAlign: TextAlign.center),
                SizedBox(width: 10),
                Icon(Icons.arrow_forward_ios, size: 15, color: colors["white"])
              ]),
              onClick: () { Navigator.pushNamed(context, 'news-detail', arguments: { "new": n, "ss": ss }); },
            ), colors: primaryColors),
            SizedBox(width: 10),
            Expanded(
              child: neuButton(NeumorphicButton(
                padding: EdgeInsets.all(20),
                style: neuButtonStyle(),
                child: Row(children: <Widget>[
                  Expanded(child: Text("Ver noticias", style: Theme.of(context).textTheme.body1.copyWith(color: colors["white"]), textAlign: TextAlign.center, overflow: TextOverflow.ellipsis)),
                  SizedBox(width: 10),
                  Icon(Icons.arrow_forward_ios, size: 15, color: colors["white"])
                ]),
                onClick: () { Navigator.pushNamed(context, 'news'); },
              ), colors: secondaryShadow),
            )
          ])
        ]), padding: EdgeInsets.all(20), width: double.infinity),
        SizedBox(height: 20)
      ],
    );
  }

  _lastSessionBenchmark(BuildContext context, Map<String,dynamic> last_session_benchmark, SubscriptionSelection ss, AuthProvider auth) {
    BITrainingSession ts = last_session_benchmark["ts"];
    UserBenchmark benchmark = last_session_benchmark["benchmark"];
    if(ts==null) return Container();
    else {
      return Column(
        children: <Widget>[
          _lastSessionBenchmarkCard(context,ts, auth),
          //_generateBenchmark(context,last_session_benchmark['benchmark'],last_session_benchmark['workout']),
          SizedBox(height: 20)
        ],
      ); //TODO: Ivan next training session
    }
  }

  _lastSessionBenchmarkCard(BuildContext context, BITrainingSession ts, AuthProvider auth) {
    String periodo;
    if (ts.date_start.toLocal().day == DateTime.now().day) {
      if (ts.date_start.toLocal().hour < 14) periodo = "Tuviste entrenamiento esta mañana";
      else if (ts.date_start.toLocal().hour >= 14 && ts.date_start.toLocal().hour < 20) periodo = "Tuviste entrenamiento esta tarde";
      else if (ts.date_start.toLocal().hour >= 20) periodo = "Tuviste entrenamiento esta noche";
    } else if (ts.date_start.toLocal().day+1 == DateTime.now().day) {
      periodo = "Tuviste entrenamiento ayer";
    } else periodo = "Tuviste entreno hace unos dias";
    return Container(
      child: neuContainer(
        Container(
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              ClipRRect(borderRadius: BorderRadius.circular(8), child: Image(image: AssetImage("assets/img/benchmark.jpg"), width: double.infinity, height: 150, fit: BoxFit.cover)),
              SizedBox(height: 20.0),
              Text("¡No olvides entrar el resultado!", style: Theme.of(context).textTheme.title.copyWith(fontSize: 20.0),),
              SizedBox(height: 10.0),
              Text("${periodo}", style: Theme.of(context).textTheme.title.copyWith(fontSize: 16.0),),
              SizedBox(height: 10.0),
              Text('${DateFormat('dd/MM/yyyy').format(ts.date_start.toLocal())} - ${DateFormat('kk:mm').format(ts.date_start.toLocal())}', style: Theme.of(context).textTheme.subtitle.copyWith(fontSize: 14.0)),
              SizedBox(height: 20.0),
              Container(
                width: double.infinity,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      width: 110,
                      child: _getParticipants(context, ts.users, auth.currentUser),
                    ),
                    SizedBox(width: 20.0),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text("${ts.users.length} atletas han participado", style: Theme.of(context).textTheme.body1.copyWith(fontSize: 14.0)),
                        SizedBox(height: 5.0),
                        neuChip(
                          Text('${ts.training_type.name}',style: TextStyle(color: Colors.white),),
                          colors: colors_list[colors_type[ts.training_type.slug]],
                          padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0)
                        )
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(height: 20.0,),
              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('Entrar resultado', style: TextStyle(color: colors['five'])),
                          Icon(MyFlutterApp.pencil, color: colors['five'],size: 15.0)
                        ],
                        spacing: 5,
                        runSpacing: 5,
                        alignment: WrapAlignment.center
                      ),
                      onClick: () {
                        Navigator.pushNamed(context, 'user-benchmark-create', arguments: ts);
                      }
                    ),
                    colors: generateGradient(235, 235, 235),
                    borderRadius: BorderRadius.circular(30),
                  )
                ],
              )     
            ],
          ),
        )
      )
    );
  }

  _nextTrainingSession(BuildContext context, BITrainingSession ts, AuthProvider auth) {
    if(ts==null || ts.id==null) return Container();
    else return Column(
      children: <Widget>[
        _nextTrainingSessionCard(context,ts,auth),
        SizedBox(height: 20)
      ],
    ); //TODO: Ivan next training session
  }

  _nextTrainingSessionCard(BuildContext context, BITrainingSession ts, AuthProvider auth) {
    String periodo;
    if (ts.date_start.toLocal().day == DateTime.now().day) {
      if (ts.date_start.toLocal().hour < 14) periodo = "Tienes entrenamiento esta mañana";
      else if (ts.date_start.toLocal().hour >= 14 && ts.date_start.toLocal().hour < 20) periodo = "Tienes entrenamiento esta tarde";
      else if (ts.date_start.toLocal().hour >= 20) periodo = "Tienes entrenamiento esta noche";
    } else if (ts.date_start.toLocal().day-1 == DateTime.now().day) {
      periodo = "Tienes entrenamiento mañana";
    } else periodo = "Tienes entreno próximamente";
    return Container(
      child: neuContainer(
        Container(
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              ClipRRect(borderRadius: BorderRadius.circular(8), child: Image(image: AssetImage("assets/img/training_session.jpg"), width: double.infinity, height: 150, fit: BoxFit.cover)),
              SizedBox(height: 20.0),
              Text("¡No llegues tarde!", style: Theme.of(context).textTheme.title.copyWith(fontSize: 20.0),),
              SizedBox(height: 10.0),
              Text("${periodo}", style: Theme.of(context).textTheme.title.copyWith(fontSize: 16.0),),
              SizedBox(height: 10.0),
              Text('${DateFormat('dd/MM/yyyy').format(ts.date_start.toLocal())} - ${DateFormat('kk:mm').format(ts.date_start.toLocal())}', style: Theme.of(context).textTheme.subtitle.copyWith(fontSize: 14.0)),
              SizedBox(height: 20.0),
              Container(
                width: double.infinity,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      width: 110,
                      child: _getParticipants(context, ts.users, auth.currentUser),
                    ),
                    SizedBox(width: 20.0),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text("${ts.users.length-1} te acompañarán", style: Theme.of(context).textTheme.body1.copyWith(fontSize: 14.0)),
                        SizedBox(height: 5.0),
                        neuChip(
                          Text('${ts.training_type.name}',style: TextStyle(color: Colors.white),),
                          colors: colors_list[colors_type[ts.training_type.slug]],
                          padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0)
                        )
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(height: 20.0,),
              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 detalles de la sesión', 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, 'training-session-detail', arguments: {"trainingSession": ts, "day": ts.date_start});
                      }
                    ),
                    colors: generateGradient(235, 235, 235),
                    borderRadius: BorderRadius.circular(30),
                  )
                ],
              )     
            ],
          ),
        )
      )
    );
  }

  _shouldTrainMoreCard(BuildContext context, bool shouldTrainMore, SubscriptionSelection ss) {
    if(shouldTrainMore) {
      return Column(
        children: <Widget>[
          neuContainer(Column(children: [
            shaderContainer(Icon(MyFlutterApp.sofa, size: 130,), 'letter', [colors["primary"], colors["secondary"]]),
            SizedBox(height: 20),
            Text("Vaya, parece que no has entrenado últimamente... ¡Apúntate a una de las sesiones que se harán próximamente!", style: Theme.of(context).textTheme.body1, textAlign: TextAlign.center,),
            SizedBox(height: 40),
            neuButton(NeumorphicButton(
              padding: EdgeInsets.all(20),
              style: neuButtonStyle(),
              child: Row(children: <Widget>[
                Expanded(child: Text("Ver sesiones de entrenamiento", style: Theme.of(context).textTheme.body1.copyWith(fontWeight: FontWeight.w500, color: colors["primary"]), textAlign: TextAlign.center,)),
                SizedBox(width: 15),
                Icon(Icons.arrow_forward_ios, size: 15, color: colors["primary"])
              ]),
              boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(30)),
              onClick: () {
                final scaffold = Provider.of<MainScaffoldProvider>(context, listen: false);
                scaffold.setPage(1);
              },
            ), borderRadius: BorderRadius.circular(30))
          ])),
          SizedBox(height: 20),
        ],
      );
    }
    else return Container();
  }

  _happyBirthday(BuildContext context, List<User> users, SubscriptionSelection ss) {
    if(users.length > 0) {
      //check if it's my birthday
      bool my_birthday = false;
      for(final u in users) {
        if(u.id == ss.us.user_id) {
          my_birthday = true;
          break;
        }
      }

      return Column(children: <Widget>[
        neuContainer(Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
          ClipRRect(borderRadius: BorderRadius.circular(8), child: Image(image: AssetImage("assets/img/happy_birthday.jpg"), width: double.infinity, height: 150, fit: BoxFit.cover)),
          SizedBox(height: 20),
          Text(my_birthday ? "Feliz cumpleaños!" : "Hoy es el aniversario de...", style: Theme.of(context).textTheme.title),
          SizedBox(height: 10),
          Text("Hoy cumplen años los siguientes atletas de tu box: ", style: Theme.of(context).textTheme.body1),
          SizedBox(height: 10),
          Container(
            width: double.infinity,
            child: Wrap(runSpacing: 10, spacing: 10, alignment: WrapAlignment.start, children: users.map((u) {
              return neuProfilePhoto(context, u, user_id: ss.us.user_id, sizeOutside: 75, sizeInside: 65);
            }).toList()),
          ),
          SizedBox(height: 20),
          Text(my_birthday ? "No te olvides de hacer tus burpees de cumpleaños cuando vayas al box!" : "Recuérdales hacer los burpees de cumpleaños cuando los veas!", style: Theme.of(context).textTheme.body1),
        ])),
        SizedBox(height: 20)
      ]);
    }
    else return Container();
  }

  _aboutMyBox(BuildContext context, SubscriptionSelection ss) {
    return neuContainer(Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text("Sobre el box", style: Theme.of(context).textTheme.title),
      SizedBox(height: 20),
      Text("A continuación tienes información de contacto con tu box:", style: Theme.of(context).textTheme.body1),
      SizedBox(height: 20),
      neuButton(NeumorphicButton(
        padding: EdgeInsets.all(20),
        style: neuButtonStyle(),
        child: Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
          Icon(Icons.navigation, color: colors["white"],),
          SizedBox(width: 20),
          Text("Ver en el mapa", style: Theme.of(context).textTheme.display2)
        ]),
        onClick: () async {
          final query = "${ss.box.address} ${ss.box.city} ${ss.box.postal_code} ${ss.box.country}";
          String url;
          if(Platform.isIOS) {
            url = Uri.encodeFull("http://maps.apple.com/?q=$query");
          }
          else if(Platform.isAndroid) {
            url = Uri.encodeFull("geo:0,0?q=$query");
          }

          if(url!=null && await canLaunch(url)) {
            launch(url);
          }
        },
      ), colors: secondaryShadow),
      SizedBox(height: 20),
      MyOrderDetailPage.contactButtons(context, ss.box)
    ]), width: double.infinity);
  }

  
  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>[
                neuChip(
                  Text('${ts.training_type.name}',style: TextStyle(color: Colors.white),),
                  colors: colors_list[colors_type[ts.training_type.slug]]
                ),
                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)
                ),
              ],
            ),
            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": DateFormat('').format(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.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Stack(
                alignment: Alignment.centerRight,
                children: new List.generate(user_size, (i) => _getImageParticipant(context,users[i],i,user_size,user)),
              ),
            ],
          ),
        ),
      )
    :
      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 );
  }
}