import 'dart:convert';
import 'dart:io';
import 'package:app_hit_a_wod/src/blocs/user_edit_form.bloc.dart';
import 'package:app_hit_a_wod/src/models/bi_training_session.model.dart';
import 'package:app_hit_a_wod/src/models/training_room.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_line.model.dart';
import 'package:app_hit_a_wod/src/models/user_benchmark_section.model.dart';
import 'package:app_hit_a_wod/src/providers/auth.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';


class UserBenchmarkDetailPage extends StatelessWidget {
  int _selectedLvl = 0;
  Widget build(BuildContext context) {
    final double formWidth = 80;
    final auth = Provider.of<AuthProvider>(context);
    Map<String,dynamic> arguments = ModalRoute.of(context).settings.arguments;
    final UserBenchmark ub = arguments['user-benchmark'];
    final TrainingWorkout tw = arguments['training-workout'];
    this._selectedLvl = ub.level=='RX' ? 0 : ub.level=='SC' ? 1 : 2;
    final UserEditFormBloc bloc = UserEditFormBloc(user: auth.currentUser);

    return neuScaffoldDetail(
      context: context,
      title: Text("Resultado del 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: Container(
          width: double.infinity,
          child: Column(
            children: <Widget>[
              Text("${tw.name!=null ? tw.name : ''}", style: Theme.of(context).textTheme.subtitle2),
              SizedBox(height: tw.name!=null ? 5.0 : 0,),
              Text('${DateFormat('dd').format(ub.created_at)} de ${DateFormat('MMMM').format(ub.created_at)} del ${DateFormat('yyyy').format(ub.created_at)}', style: Theme.of(context).textTheme.body1),
              SizedBox(height: 20.0,),
              getMiniWorkout(context, tw),
              SizedBox(height: 20.0,),
              _getWorkout(context, tw, ub)
            ],
          )
        )
      )
    );
  }

  _getWorkout(BuildContext context, TrainingWorkout tw, UserBenchmark ub) {
    return neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Expanded(child: Text("Workout", style: Theme.of(context).textTheme.subtitle2,)),
              neuChip(
                Text("${ub.level}", style: TextStyle(color: Colors.white),)
              ),
            ],
          ),
          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],ub.user_benchmark_sections[i]))
          )        ],
      ),
      width: double.infinity
    );
  }

  _generateSections(BuildContext context, TrainingWorkoutSection ts, UserBenchmarkSection ubs) {
    return neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Wrap(
            runSpacing: 10.0,
            spacing: 10.0,
            children: <Widget>[
              Row(
                children: <Widget>[
                  Expanded(child: Text("${ts.type}", style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 16.0),)),
                  _generateBenchmarkSectionCompleted(context,ubs)
                ],
              ),
              ubs.rounds!=null ? 
              neuChip(
                Text("${ubs.rounds} rondas", style: TextStyle(color: Colors.white),),
                colors: secondaryShadow
              ) : SizedBox(),
              ubs.time!=null ? neuChip(
                Text("${ubs.time}", style: TextStyle(color: Colors.white),)
              ) : SizedBox()
            ],
          ),
          (ubs.rounds!=null || ubs.time!=null) ? SizedBox(height: 10.0,) : SizedBox(),
          Text("${ts.description}", style: Theme.of(context).textTheme.body1,),
          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],ubs.user_benchmark_lines[i]))
            ),
          )
        ],
      ),
      width: double.infinity
    );
  }

  _generateExercises(BuildContext context, TrainingWorkoutLine twl, UserBenchmarkLine ubl) {
    final options = {
      "seconds": (_selectedLvl==0) ? twl.seconds : twl.seconds_scaled,
      "reps": (_selectedLvl==0) ? twl.reps : twl.reps_scaled,
      "maleVal": (_selectedLvl==0) ? twl.maleVal : twl.maleVal_scaled,
      "femaleVal": (_selectedLvl==0) ? twl.femaleVal : twl.femaleVal_scaled,
      "units": (_selectedLvl==0) ? twl.units : twl.units_scaled,
    };
    return neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Expanded(child: Text("${(_selectedLvl==0) ? twl.exercise.name : twl.exercise_scaled.name}", style: Theme.of(context).textTheme.subtitle.copyWith(fontSize: 16),)),
              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,),
            ],
          ),
          ubl.val!=null || ubl.reps!=null ? SizedBox(height: 10.0,) : SizedBox(),
          twl.description!=null && twl.description.isNotEmpty ? Text("${twl.description!=null && twl.description.isNotEmpty ? twl.description : ''}", style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 12, fontStyle: FontStyle.italic),) : SizedBox(),
          ubl.val!=null ? SizedBox(height: 10.0,) : SizedBox(),
          ubl.val!=null ? Text("${ubl.val!=null ? ubl.val : ''} ${ubl.units!=null ? ubl.units : ''}", style: Theme.of(context).textTheme.body1,) : SizedBox(),
          ubl.reps!=null ? SizedBox(height: 10.0,) : SizedBox(),
          ubl.reps!=null ? Text("${ubl.reps!=null ? ubl.reps.toString().split('.')[0] + ' reps' : ''}", style: Theme.of(context).textTheme.body1,) : SizedBox(),
          ubl.val==null && ubl.reps==null ? SizedBox(height: 10.0,) : SizedBox(),
          ubl.val==null && ubl.reps==null ? Text("Ejercicio no evaluable", style: Theme.of(context).textTheme.body1.copyWith(fontSize: 14.0),) : SizedBox() 
        ],
      ),
      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);
    }
  }
}