import 'dart:convert';
import 'dart:io';
import 'package:app_hit_a_wod/src/blocs/exercise.bloc.dart';
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/bi_exercises.model.dart';
import 'package:app_hit_a_wod/src/models/exercise.model.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.dart';
import 'package:app_hit_a_wod/src/utils/fontello/my_flutter_app_icons.dart';
import 'package:app_hit_a_wod/src/utils/indicator.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';
import 'package:fl_chart/fl_chart.dart';
import 'package:video_player/video_player.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';

class ExerciseDetailPage extends StatelessWidget {

  
  Widget build(BuildContext context) {
    YoutubePlayerController _youtubeController;
    final _api = Provider.of<ApiProvider>(context);
    final double formWidth = 80;
    final auth = Provider.of<AuthProvider>(context);
    final UserSubscriptionsProvider us_provider = Provider.of<UserSubscriptionsProvider>(context);
    final Exercise exercise = ModalRoute.of(context).settings.arguments;
    final level = ['Fácil','Medio','Difícil'];
    final ExerciseBloc bloc = ExerciseBloc(context: context, user_id: auth.currentUser.id, exercise_id: exercise.id);
    if(exercise.url_video_predefined!=null && (exercise.url_video_predefined.contains('embed') || exercise.url_video_predefined.contains('watch?v='))) {
      _youtubeController = YoutubePlayerController(
        initialVideoId: YoutubePlayer.convertUrlToId(exercise.url_video_predefined),
        flags: YoutubePlayerFlags(
          mute: true,
          autoPlay: true,
          disableDragSeek: false,
          loop: true,
          isLive: false,
          forceHD: false,
          enableCaption: true,
        ),
      );
    }

    return neuScaffoldDetail(
      context: context,
      title: Text("Ejercicio", 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: Container(
          width: double.infinity,
          child: Column(
            children: <Widget>[
              Text('${exercise.name}', style: Theme.of(context).textTheme.subtitle2),
              neuContainer(
                Column(
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Expanded(child: Text("Descripción", style: Theme.of(context).textTheme.subtitle2,)),
                        neuChip(
                          Text('${level[exercise.level-1]}',style: Theme.of(context).textTheme.display2,),
                          colors: colors_list[colors_level[exercise.level.toString()]]
                        ),
                      ],
                    ),
                    SizedBox(height: 20.0,),
                    Container(
                      width: double.infinity,
                      child: Wrap(
                        spacing: 10.0,
                        runSpacing: 10.0,
                        crossAxisAlignment: WrapCrossAlignment.center,
                        alignment: WrapAlignment.start,
                        children: <Widget>[
                          Container(
                            child: exercise.type!=null ? neuChip(
                              Text('${exercise.type}',style: Theme.of(context).textTheme.display2,)
                            ) : SizedBox(),
                          ),
                          Container(
                            child: neuChip(
                              Container(
                                child: Wrap(
                                  children: <Widget>[
                                    Icon(MyFlutterApp.kettlebell, size: 14.0, color: Colors.white,),
                                    SizedBox(width: 5),
                                    Text("${(exercise.equipment_type!=null) ? ' '+exercise.equipment_type : ' Sin equipamiento'}", style: Theme.of(context).textTheme.display2,)
                                  ],
                                ),
                              ),
                              colors: colors_list['secondary']
                            )
                          )
                        ],
                      ),
                    ),
                    (exercise.url_video_predefined!=null && (exercise.url_video_predefined.contains('embed') || exercise.url_video_predefined.contains('watch?v='))) ? SizedBox(height: 20.0,) : SizedBox(),
                    
                    (exercise.url_video_predefined!=null && (exercise.url_video_predefined.contains('embed') || exercise.url_video_predefined.contains('watch?v='))) ? ClipRRect(
                      borderRadius: BorderRadius.circular(16),
                      child: YoutubePlayer(
                        controller: _youtubeController,
                        showVideoProgressIndicator: true,
                        progressIndicatorColor: colors['primary'],
                        /* onEnded: (data) {
                          _youtubeController.load((exercise.url_video_predefined.split('embed/'))[1]);
                        }, */
                      ),
                    ) : SizedBox(),
                    SizedBox(height: 20.0,),
                    Container(
                      child: Text("${exercise.description!=null ? exercise.description : ''}", style: Theme.of(context).textTheme.bodyText2,)
                    )
                  ],
                ),
                margin: EdgeInsets.only(top: 20),
                width: double.infinity
              ),
              //(exercise.graph!=null) ? _graph(exercise.graph) : SizedBox()
              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) {
                  if(data.hasData) {
                    List<UserBenchmark> benchmarks = data.data["benchmarks"].benchmarks;
                    List<TrainingWorkout> workouts = data.data["benchmarks"].workouts;
                    List<Map<String,dynamic>> graph = data.data["benchmarks"].graph;
                    
                    return Column(
                      children: <Widget>[
                        Container(
                          width: double.infinity,
                          child: ((data.connectionState == ConnectionState.active && data.hasData && benchmarks!=null && benchmarks.length>0) ? 
                                _getBenchmarks(context,benchmarks,workouts)
                                : SizedBox()),
                        ),
                        SizedBox(height: 20.0,),
                        _socreGraph(context,graph)
                      ],
                    );
                  } else return Container();
                }
              )
            ],
          )
        )
      )
    );
  }

  _socreGraph(BuildContext context, List<Map<String,dynamic>> data) {
    if(data.length==0) {
      return SizedBox();
    }
    else {
      final double width = 7;
      final Color wodBarColor = colors["primary"];
      final Color openBarColor = colors["secondary"];
      
      var max = 0;
      List<BarChartGroupData> barGroups = List();
      List<String> datas = [];
      data.forEach((element) { 
        datas.add(element['name']);
        if (max<element['value']) max = element['value'];
        barGroups.add(
        BarChartGroupData(
          barsSpace: 4.0,
          x: int.parse(element['name'].split('/').join('')),
          barRods: [
            BarChartRodData(y: element['value'].toDouble(), color: wodBarColor, width: width),
          ]
        )); 
      });

      return neuContainer(
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(children: <Widget>[
              Text("Puntuaciones", style: Theme.of(context).textTheme.title),
              SizedBox(width: 20)
            ],),
            SizedBox(height: 20),
            BarChart(BarChartData(
              barGroups: barGroups,
              titlesData: FlTitlesData(
                show: true,
                bottomTitles: SideTitles(
                  showTitles: true,
                  getTitles: (value) {
                    if (value == 0 || value == datas.length-1 ||  value == ((datas.length-1)/2).toInt()) return  datas[value.toInt()];
                    else return '';
                  },
                  margin: 20,
                  reservedSize: 20,
                  textStyle: Theme.of(context).textTheme.overline.copyWith(fontSize: 10),
                ),
                leftTitles: SideTitles(
                  showTitles: true,
                  getTitles: (val) => val.toInt().toString(),
                  margin: 20,
                  reservedSize: 20,
                  interval: max>0 ? ((max/5)+1).floor().toDouble() : 1,
                  textStyle: Theme.of(context).textTheme.overline
                )
              ),
              borderData: FlBorderData( show: false )
            ))
          ],
        ),
        padding: EdgeInsets.symmetric(vertical: 35, horizontal: 30),
        width: double.infinity
      );
    }
  }

  _getBenchmarks(BuildContext context, List<UserBenchmark> benchmarks, List<TrainingWorkout> workouts) {
    return neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text('Útilmos 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],workouts[i])),
          )
        ],
      ),
      margin: EdgeInsets.only(top: 20.0),
      width: double.infinity
    );
  }

  _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)}")
                ),
              )
            ],
          ),
          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);
    }
  }
}