import 'dart:convert';
import 'dart:io';
import 'package:app_hit_a_wod/src/blocs/training_workout.bloc.dart';
import 'package:app_hit_a_wod/src/blocs/user_edit_form.bloc.dart';
import 'package:app_hit_a_wod/src/models/training_workout.model.dart';
import 'package:app_hit_a_wod/src/models/training_workout_line.model.dart';
import 'package:app_hit_a_wod/src/models/training_workout_section.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/providers/api.provider.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/fontello/my_flutter_app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import 'package:rxdart/rxdart.dart';


class TrainingWorkoutDetailPage extends StatelessWidget {
  Widget build(BuildContext context) {
    final _api = Provider.of<ApiProvider>(context);
    final auth = Provider.of<AuthProvider>(context);
    final UserSubscriptionsProvider us_provider = Provider.of<UserSubscriptionsProvider>(context);
    final TrainingWorkout tw = ModalRoute.of(context).settings.arguments;
    final TrainingWorkoutPageBloc bloc = TrainingWorkoutPageBloc(context: context, user_id: auth.currentUser.id, workout_id: tw.id, user: auth.currentUser);

    return neuScaffoldDetail(
      context: context,
      title: Text("Workout", style: Theme.of(context).textTheme.subhead.copyWith(fontWeight: FontWeight.w500, fontSize: 18)),
      action: FlatButton(
        child: shaderContainer(Image.asset('assets/icon/logo.png', height: 35, width: 35,),'in'),
        onPressed: () {
          Navigator.of(context).popUntil(ModalRoute.withName('home'));
        }
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(20),
        child: Column(
          children: <Widget>[
            StreamBuilder(
              stream: CombineLatestStream.combine2(auth.userStream, us_provider.activeStream, (user, ss) => {"user": user, "ss": ss}),
              builder: (BuildContext context, AsyncSnapshot<dynamic> data) {
                return Container(
                  width: double.infinity,
                  child: ((data.connectionState == ConnectionState.active && data.hasData) ? 
                    _getHeader(context, tw, data.data["user"], _api,auth, bloc)
                    : (Container(
                        width: double.infinity,
                        child: Row(
                          children: <Widget>[
                            SizedBox(height: 60.0, width: 60.0,),
                            Expanded(
                              child: Column(
                                children: <Widget>[
                                  Container(
                                    alignment: Alignment.center,
                                    child: Text("${tw.category}", style: Theme.of(context).textTheme.subtitle, textAlign: TextAlign.center)
                                  ),
                                  Container(
                                    alignment: Alignment.center,
                                    child: Text("${tw.name}", style: Theme.of(context).textTheme.subtitle, textAlign: TextAlign.center)
                                  ),
                                ],
                              )
                            ),
                            neuButtonCircular(
                              NeumorphicButton(
                                padding: EdgeInsets.all(20),
                                style: neuButtonStyle(),
                                boxShape: NeumorphicBoxShape.circle(),
                                child: Icon(Icons.favorite, color: Colors.grey),
                                onClick: () {}
                              ),
                            ),
                          ],
                        ),
                      )
                    )
                  ),
                );
              }
            ),
            _getDescription(context, tw),
            _getWorkout(context, tw, bloc),
            StreamBuilder(
              stream: CombineLatestStream.combine3(auth.userStream, us_provider.activeStream, bloc.benchmarksStream, (user, ss, benchmarks) => {"user": user, "ss": ss, "benchmarks": benchmarks}),
              builder: (BuildContext context, AsyncSnapshot<dynamic> data) {
                return Container(
                  width: double.infinity,
                  child: ((data.connectionState == ConnectionState.active && data.hasData) ? 
                        _getBenchmarks(context,data.data["benchmarks"],data, tw)
                        : SizedBox()),
                );
              }
            ),
          ],
        )
      )
    );
  }

  _getHeader(BuildContext context,TrainingWorkout tw, User user, ApiProvider _api, AuthProvider auth, TrainingWorkoutPageBloc bloc) {
    return Container(
      width: double.infinity,
      child: Row(
        children: <Widget>[
          SizedBox(height: 60.0, width: 60.0,),
          Expanded(
            child: Column(
              children: <Widget>[
                Container(
                  alignment: Alignment.center,
                  child: Text("${tw.category}", style: Theme.of(context).textTheme.subtitle.copyWith(fontWeight: FontWeight.w400), textAlign: TextAlign.center)
                ),
                Container(
                  alignment: Alignment.center,
                  child: Text("${tw.name}", style: Theme.of(context).textTheme.subtitle, textAlign: TextAlign.center)
                ),
              ],
            )
          ),
          _getFavorite(context,tw,user,_api, auth, bloc),
        ],
      ),
    );
  }

  _getFavorite(BuildContext context,TrainingWorkout tw, User user, ApiProvider _api, AuthProvider auth, TrainingWorkoutPageBloc bloc) {
    return StreamBuilder(
      stream: bloc.favoriteStream,
      builder: (context, data) {
        if(data.hasData) {
          return neuButtonCircular(
            NeumorphicButton(
              padding: EdgeInsets.all(20),
              style: neuButtonStyle(),
              boxShape: NeumorphicBoxShape.circle(),
              child: Icon(Icons.favorite, color: (bloc.favoriteValue) ? Colors.red : Colors.grey),
              onClick: () {
                _api.updateUserFavoriteWorkouts(user.id, tw.id);
                bloc.favoriteSet(!bloc.favoriteValue);
                if(bloc.favoriteValue) auth.currentUser.favorite_workouts_ids.add(tw.id);
                else auth.currentUser.favorite_workouts_ids.remove(tw.id);
              }
            ),
          );
        }
        else return Container();
      },
    );
  }

  _getDescription(BuildContext context, TrainingWorkout tw) {
    return neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Expanded(child: Text("Descripción", style: Theme.of(context).textTheme.subtitle2,)),
              neuChip(
                Text("${tw.category}",style: TextStyle(color: Colors.white))
              )
            ],
          ),
          SizedBox(height: 20.0,),
          Text("${tw.description!=null && !tw.description.isEmpty ? tw.description : 'No hay descripción para este workout.'}", style: Theme.of(context).textTheme.bodyText2,)
        ],
      ),
      margin: EdgeInsets.symmetric(vertical: 20.0),
      width: double.infinity
    );
  }

  _getWorkout(BuildContext context, TrainingWorkout tw, TrainingWorkoutPageBloc bloc) {
    return StreamBuilder(
      stream: bloc.selectedLvlStream,
      builder: (context, snapshot) {
        return neuContainer(
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                children: <Widget>[
                  Expanded(child: Text("Workout", style: Theme.of(context).textTheme.subtitle2,)),
                  NeumorphicToggle(
                    style: NeumorphicToggleStyle(backgroundColor: neuColor, borderRadius: BorderRadius.circular(8)),
                    width: 150.0,
                    height: 50.0,
                    selectedIndex: bloc.selectedLvlValue,
                    displayForegroundOnlyIfSelected: true,
                    children: [
                      ToggleElement(
                        background: Center(
                          child: Text('RX', style: Theme.of(context).textTheme.body1),
                        ),
                        foreground: Center(
                          child: shaderContainer(Text('RX', style: Theme.of(context).textTheme.body1.copyWith(fontWeight: FontWeight.w500)), 'letter', primaryColors),
                        )
                      ),
                      ToggleElement(
                        background: Center(
                          child: Text('SC', style: Theme.of(context).textTheme.body1),
                        ),
                        foreground: Center(
                          child: shaderContainer(Text('SC', style: Theme.of(context).textTheme.body1.copyWith(fontWeight: FontWeight.w500)), 'letter', primaryColors),
                        ),
                      ),
                    ],
                    thumb: Neumorphic(
                      style: neuStyle(),
                    ),
                    onChanged: (value) {
                      bloc.selectedLvlSet(value);
                    },
                  ),
                ],
              ),
              SizedBox(height: 20.0,),
              Wrap(
                runSpacing: 20.0,
                children: new List.generate(tw.training_workout_sections.length, (i) => _generateSections(context,tw.training_workout_sections[i], bloc))
              )        ],
          ),
          width: double.infinity
        );
      }
    );
  }

  _generateSections(BuildContext context, TrainingWorkoutSection ts, TrainingWorkoutPageBloc bloc) {
    return neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Expanded(child: Text("${ts.type}", style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 16.0),)),
              SizedBox(width: 10.0,),
              ts.rounds!=null ? 
                neuChip(
                  Text("${ts.rounds} rondas", style: TextStyle(color: Colors.white),),
                  colors: secondaryShadow
                ) : ts.seconds!=null ? neuChip(
                    Text("${ts.type=='For Time' ? 'Time cap: ' : ''}${[Duration(seconds: ts.seconds).inHours, Duration(seconds: ts.seconds).inMinutes, Duration(seconds: ts.seconds).inSeconds].map((seg) => seg.remainder(60).toString().padLeft(2, '0')).join(':')}", style: TextStyle(color: Colors.white),)
                  ) : SizedBox(height: 0.0, width: 0.0,),
            ],
          ),
          SizedBox(height: 10),
          ts.seconds!=null && ts.rounds!=null ? neuChip(
            Text("${ts.type=='For Time' ? 'Time cap: ' : ''}${[Duration(seconds: ts.seconds).inHours, Duration(seconds: ts.seconds).inMinutes, Duration(seconds: ts.seconds).inSeconds].map((seg) => seg.remainder(60).toString().padLeft(2, '0')).join(':')}", style: TextStyle(color: Colors.white),)
          ) : SizedBox(height: 0.0, width: 0.0,),
          SizedBox(height: 10),
          (
            ts.description!=null ?
            Text("${ts.description}", style: Theme.of(context).textTheme.body1) :
            Container()
          ),
          Container(
            margin: EdgeInsets.only(top: 20.0),
            child: Wrap(
              runSpacing: 20.0,
              children: new List.generate(ts.lines.length, (i) => _generateExercises(context,ts.lines[i],bloc))
            ),
          )
        ],
      ),
      width: double.infinity
    );
  }

  _generateExercises(BuildContext context, TrainingWorkoutLine line, TrainingWorkoutPageBloc bloc) {
    final options = {
      "seconds": (bloc.selectedLvlValue==0) ? line.seconds : line.seconds_scaled,
      "reps": (bloc.selectedLvlValue==0) ? line.reps : line.reps_scaled,
      "maleVal": (bloc.selectedLvlValue==0) ? line.maleVal : line.maleVal_scaled,
      "femaleVal": (bloc.selectedLvlValue==0) ? line.femaleVal : line.femaleVal_scaled,
      "units": (bloc.selectedLvlValue==0) ? line.units : line.units_scaled,
    };
    return neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Expanded(child: Text("${(bloc.selectedLvlValue==0) ? line.exercise.name : line.exercise_scaled.name}", style: Theme.of(context).textTheme.subtitle.copyWith(fontSize: 14),)),
              SizedBox(height: 20.0,),
              options['seconds']!=null ? 
                neuChip(
                  Text("${[Duration(seconds: options['seconds']).inHours, Duration(seconds: options['seconds']).inMinutes, Duration(seconds: options['seconds']).inSeconds].map((seg) => seg.remainder(60).toString().padLeft(2, '0')).join(':')}", style: TextStyle(color: Colors.white),)
                ) : SizedBox(height: 0.0, width: 0.0,),
            ],
          ),
          SizedBox(height: 10.0,),
          Text("${line.description!=null ? line.description : ''}", style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 12, fontStyle: FontStyle.italic),),
          (line.description!=null) ? SizedBox(height: 10.0, width: 5.0,) : SizedBox(),
          Wrap(
            children: <Widget>[
              Text("${(bloc.selectedLvlValue==0) ? (line.reps!=null ? line.reps+' reps, ' : '') : (line.reps_scaled!=null ? line.reps_scaled+' reps, ' : '')}", style: Theme.of(context).textTheme.display1.copyWith(fontSize: 14.0)),
              ( options['maleVal']!=null || options['femaleVal']!=null || options['units']!=null ) ? 
                Text("${options['maleVal']!=null ? options['maleVal'] : ''}${options['femaleVal']!=null ? ' / ' + options['femaleVal'] : ''} ${options['units']!=null ? options['units'] : ''}", style: Theme.of(context).textTheme.display1.copyWith(fontSize: 14.0),)
                :
                SizedBox(),
            ],
          ),
          SizedBox(height: 10.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(
                    spacing: 5,
                    runSpacing: 5,
                    alignment: WrapAlignment.center,
                    crossAxisAlignment: WrapCrossAlignment.center,
                    children: <Widget>[
                      Text('Ver Ejercicio', style: TextStyle(color: colors['primary']),),
                      Icon(MyFlutterApp.right_arrow, color: colors['primary'],size: 15.0)
                    ],
                  ),
                  onClick: () {
                    Navigator.pushNamed(context, 'exercise-detail', arguments: (bloc.selectedLvlValue==0) ? line.exercise : line.exercise_scaled);
                  }
                )
              )
            ],
          )
        ],
      ),
      width: double.infinity
    );
  }

  _getBenchmarks(BuildContext context, List<UserBenchmark> benchmarks,AsyncSnapshot<dynamic> data, TrainingWorkout tw) {
    return (benchmarks.length>0) ? neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text('Últimos registros', style: Theme.of(context).textTheme.subtitle2),
          SizedBox(height: 20.0,),
          Wrap(
            runSpacing: 20.0,
            children: new List.generate((benchmarks.length>=3) ? 3 : benchmarks.length, (i) => _generateBenchmark(context,benchmarks[i],tw)),
          )
        ],
      ),
      margin: EdgeInsets.only(top: 20.0),
      width: double.infinity
    ) : SizedBox();
  }

  _generateBenchmark(BuildContext context, UserBenchmark b, TrainingWorkout tw) {
    return neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              neuChip(
                Text("${b.score} pt.", style: TextStyle(color: Colors.white),)
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.centerRight,
                  child: Text("${DateFormat('dd/MM/yyyy').format(b.created_at)}", style: Theme.of(context).textTheme.body1)
                ),
              )
            ],
          ),
          SizedBox(height: 20.0,),
          Text("Secciones completadas", style: Theme.of(context).textTheme.subtitle.copyWith(fontSize: 16.0),),
          SizedBox(height: 20.0,),
          Wrap(
            spacing: 5.0,
            runSpacing: 5.0,
            children: new List.generate((b.user_benchmark_sections!=null) ? b.user_benchmark_sections.length : 0, (i) => _generateBenchmarkSectionCompleted(context,b.user_benchmark_sections[i]))
          ),
          SizedBox(height: 20.0,),
          Container(
            alignment: Alignment.centerRight,              
            child: 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 Resultado', 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, 'user-benchmark-detail', arguments: {'user-benchmark': b, 'training-workout': tw});
                }
              ),
              colors: generateGradient(235, 235, 235),
              borderRadius: BorderRadius.circular(30),
              
            ),
          )
        ],
      ),
      width: double.infinity
    );
  }

  _generateBenchmarkSectionCompleted(BuildContext context, UserBenchmarkSection bs) {
    if ( bs.completed == 1 ) {
      return Icon(MyFlutterApp.ok, color: Colors.green,);
    } else {
      return Icon(MyFlutterApp.cross, color: Colors.red);
    }
  }
}