import 'package:app_hit_a_wod/src/blocs/stats.bloc.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:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';


class ExerciseFilterPage 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 StatsBloc bloc = StatsBloc(
      context: context, 
      user_id: auth.currentUser.id,
      box_id: us_provider.currentActiveSubscription.box.id, 
    );
    Map<String, dynamic> arguments = ModalRoute.of(context).settings.arguments;
    final exerciseTypes = ["Abdominal","Pull-up","Static","Bike","Burpee","Jumps","Muscle-up","Cleans","Jerk","Presses","Lunges","Thruster","Climb","Curl","Deadlift","Dip","Hyperextension","Push","Jump Rope","Squat","Walking","Snatch","Push-up","Racks","Strongman","Rest","Row","Run","Swimming","Swing","Throw"];

    return neuScaffoldDetail(
      context: context,
      leading: IconButton(
        icon: Icon(Icons.arrow_back, color: Colors.transparent),
        onPressed: () {
          bloc.refreshExercises(auth.currentUser.id, us_provider.currentActiveSubscription.box.id, arguments['name']);
          Navigator.of(context).pop();
        }
      ),
      title: Text("Filtros Ejercicios", style: Theme.of(context).textTheme.subhead.copyWith(fontWeight: FontWeight.w500, fontSize: 18)),
      action: FlatButton(
        child: Text("Filtrar", style: Theme.of(context).textTheme.body1.copyWith(color: colors['primary']),),
        onPressed: () {
          bloc.refreshExercises(auth.currentUser.id, us_provider.currentActiveSubscription.box.id, arguments['name']);
          Navigator.of(context).pop();
        }
      ),
      
      body: SingleChildScrollView(
        padding: EdgeInsets.all(20),
        child: Container (
          child: Column (
            children: <Widget> [
              Container(
                width: double.infinity,
                child: Expanded(
                  child: neuButton(
                    NeumorphicButton(
                      boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(50)),
                      padding: EdgeInsets.all(15),
                      style: NeumorphicStyle(
                        color: Colors.transparent,
                        depth: neuDepth,
                      ),
                      child: Wrap(
                        crossAxisAlignment: WrapCrossAlignment.center,
                        children: <Widget>[
                          Text('Limpiar filtros y volver', style: TextStyle(color: colors['primary'])),
                          Icon(Icons.settings_backup_restore, color: colors['primary'],size: 15.0),
                        ],
                        spacing: 5,
                        runSpacing: 5,
                        alignment: WrapAlignment.center
                      ),
                      onClick: () {
                        bloc.cleanFiltersExercises();
                        bloc.refreshExercises(auth.currentUser.id, us_provider.currentActiveSubscription.box.id, arguments['name']);
                        Navigator.of(context).pop();
                      }
                    ),
                    width: 10,
                    colors: generateGradient(235, 235, 235),
                    borderRadius: BorderRadius.circular(30),
                  ),
                ),
              ),
              SizedBox(height: 20.0,),
              StreamBuilder( //llistar tarifes
                  stream: CombineLatestStream.combine2(bloc.modalityExerciseStream, bloc.difficultyExerciseStream, (a, b) => {"modality": a, "difficulty": b}),
                  builder: (context, AsyncSnapshot data) {
                    if(data.hasData) {
                      return modalityDifficulty(context,bloc);
                    } else {
                      return SizedBox();
                    }
                  }
              ),
              SizedBox(height: 20.0,),
              StreamBuilder(
                stream: bloc.equipmentExerciseStream,
                builder: (BuildContext context, AsyncSnapshot<dynamic> data) {
                  return _buttonsMaterial(context, bloc, bloc.equipmentExerciseValue);
                }
              ),
              SizedBox(height: 20.0,),
              StreamBuilder(
                stream: bloc.exerciseTypesExerciseStream,
                builder: (BuildContext context, AsyncSnapshot<dynamic> data) {
                  if(data.hasData && exerciseTypes!=null) {
                    return Column(
                      children: <Widget>[
                        titleHeader("Tipo de ejercicios"),
                        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('${bloc.exerciseTypesExerciseValue.length<=0 ? 'Marcar todo' : 'Desmarcar todos'}', style: TextStyle(color: colors['primary'])),
                                    Icon(bloc.exerciseTypesExerciseValue.length<=0 ? MyFlutterApp.ok : MyFlutterApp.cross, color: colors['primary'],size: 15.0)
                                  ],
                                  spacing: 5,
                                  runSpacing: 5,
                                  alignment: WrapAlignment.center
                                ),
                                onClick: () {
                                  if (bloc.exerciseTypesExerciseValue.length>0) {
                                    bloc.exerciseTypesExerciseSet([]);
                                  } else {
                                    bloc.exerciseTypesExerciseSet(["Abdominal","Pull-up","Static","Bike","Burpee","Jumps","Muscle-up","Cleans","Jerk","Presses","Lunges","Thruster","Climb","Curl","Deadlift","Dip","Hyperextension","Push","Jump Rope","Squat","Walking","Snatch","Push-up","Racks","Strongman","Rest","Row","Run","Swimming","Swing","Throw"]);
                                  }
                                  //Navigator.pushNamed(context, 'training-workout-detail', arguments: tw);
                                }
                              ),
                              colors: generateGradient(235, 235, 235),
                              borderRadius: BorderRadius.circular(30),
                            )
                          ],
                        ),
                        SizedBox(height: 20.0,),
                        Container(
                          width: double.infinity,
                          padding: EdgeInsets.all(5.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Expanded(
                                child: Column(
                                  children: new List.generate((exerciseTypes.length/2).toInt(), (i)=>_exerciseTypes(context, bloc,exerciseTypes[i])),
                                ),
                              ),
                              Expanded(
                                child: Column(
                                  children: new List.generate(exerciseTypes.length-(exerciseTypes.length/2).toInt(), (i)=>_exerciseTypes(context, bloc,exerciseTypes[(exerciseTypes.length/2).toInt()+i])),
                                ),
                              ),
                            ],
                          ),
                        )
                      ],
                    );
                  } else {
                    return SizedBox();
                  }
                }
              )
            ]
          )
        )
      )
    );
  }

  titleHeader(String title) {
    return Row(
      children: <Widget>[
        neuChip(Text("${title}", style: TextStyle(color: Colors.white),)),
        SizedBox(width: 20.0,),
        Expanded(
          child: Divider(color: colors['primary'],),
        )
      ],
    );
  }

  modalityDifficulty(BuildContext context, StatsBloc bloc) {
    List<String> diff = ['Fácil', 'Medio', 'Difícil'];
    return Container(
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        alignment: WrapAlignment.spaceBetween,
        children: <Widget>[
          titleHeader("Modalidad y dificultad"),
          SizedBox(height: 20.0),
          Wrap(
            spacing: 10.0,
            runSpacing: 10.0,
            crossAxisAlignment: WrapCrossAlignment.start,
            alignment: WrapAlignment.center,
            direction: Axis.vertical,
            children: <Widget>[
              SizedBox(height: 10.0),
              Row(
                children: <Widget>[
                  NeumorphicCheckbox(
                    value: bloc.modalityExerciseValue.contains('G'),
                    style: neuCheckboxStyle(),
                    onChanged: (val) {
                      List<String> s = bloc.modalityExerciseValue;
                      if(s.contains('G')) s.remove('G');
                      else s.add('G');
                      bloc.modalityExerciseSet(s);
                    }
                  ),
                  SizedBox(width: 10.0,),
                  Container(
                    width: 100,
                    child: Text('Gimnásticos')
                  )
                ],
              ),
              Row(
                children: <Widget>[
                  NeumorphicCheckbox(
                    value: bloc.modalityExerciseValue.contains('M'),
                    style: neuCheckboxStyle(),
                    onChanged: (val) {
                      List<String> s = bloc.modalityExerciseValue;
                      if(s.contains('M')) s.remove('M');
                      else s.add('M');
                      bloc.modalityExerciseSet(s);
                    }
                  ),
                  SizedBox(width: 10.0,),
                  Container(
                    width: 100,
                    child: Text('Acondicionamiento metabólico')
                  )
                ],
              ),
              Row(
                children: <Widget>[
                  NeumorphicCheckbox(
                    value: bloc.modalityExerciseValue.contains('W'),
                    style: neuCheckboxStyle(),
                    onChanged: (val) {
                      List<String> s = bloc.modalityExerciseValue;
                      if(s.contains('W')) s.remove('W');
                      else s.add('W');
                      bloc.modalityExerciseSet(s);
                    }
                  ),
                  SizedBox(width: 10.0,),
                  Container(
                    width: 100,
                    child: Text('Weightlifting')
                  )
                ],
              )
            ],
          ),
          Wrap(
            spacing: 10.0,
            runSpacing: 10.0,
            crossAxisAlignment: WrapCrossAlignment.start,
            alignment: WrapAlignment.center,
            direction: Axis.vertical,
            children: <Widget>[
              Text('Dificultad máxima', style: Theme.of(context).textTheme.body1,),
              neuContainer(
                DropdownButton<String>(
                  hint: Text("Selecciona un nivel"),
                  value: diff[bloc.difficultyExerciseValue-1],
                  isExpanded: true,
                  icon: Icon(Icons.arrow_drop_down, color: colors['primary'],),
                  underline: Container(height: 0, width: 0,),
                  items: <String>['Fácil', 'Medio', 'Difícil'].map((String value) {
                    return new DropdownMenuItem<String>(
                      value: value,
                      child: new Text("   "+value),
                    );
                  }).toList(),
                  onChanged: (value) {
                      bloc.difficultyExerciseSet(diff.indexOf(value)+1);
                  },
                ),
                width: 150,
                padding: EdgeInsets.all(2.0),
              )
            ],
          )
        ],
      ),
    );
  }

  _exerciseTypes(BuildContext context, StatsBloc bloc, String exercise) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 5.0),
      child: Row(
        children: <Widget>[
          NeumorphicCheckbox(
            value: bloc.exerciseTypesExerciseValue.contains(exercise),
            style: neuCheckboxStyle(),
            onChanged: (val) {
              List<String> s = bloc.exerciseTypesExerciseValue;
              if(s.contains(exercise)) s.remove(exercise);
              else s.add(exercise);
              bloc.exerciseTypesExerciseSet(s);
            }
          ),
          SizedBox(width: 10.0,),
          Text("${exercise}", style: Theme.of(context).textTheme.body1.copyWith(fontSize: 15.0), overflow: TextOverflow.ellipsis,)
        ],
      ),
    );
  }

  _buttonContent(Widget icon,Text text) {
    return Container(
      child: Column(
        children: <Widget>[
          icon,
          SizedBox(height: 10.0,),
          Container(
            alignment: Alignment.center,
            width: double.infinity,
            height: 30,
            child: text
          )
        ],
      ),
    );
  }

  _buttonMaterial(BuildContext context, StatsBloc bloc, List<String> equipment_exercise, String titulo, String elemento, Widget icon) {
    return neuButton (
      NeumorphicButton(
        padding: EdgeInsets.all(10),
        style: equipment_exercise.contains(elemento) ? neuStylePressed() : neuButtonStyle(),
        boxShape: neuBoxShape(),
        child: _buttonContent(icon,Text("${titulo}", style: Theme.of(context).textTheme.body1.copyWith(fontSize: 13.0, color: equipment_exercise.contains(elemento) ? colors['primary'] : Color(0xFF575F6B)), overflow: TextOverflow.fade, textAlign: TextAlign.center,)),
        onClick: () {
          List<String> e = equipment_exercise;
          if(e.contains(elemento)) e.remove(elemento);
          else e.add(elemento);
          bloc.equipmentExerciseSet(e);
        },
      ),
    );
  }

  _buttonsMaterial(BuildContext context, StatsBloc bloc, List<String> equipment_exercise) {
    return Column(
      children: <Widget>[
        titleHeader("Material"), 
        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('${bloc.equipmentExerciseValue.length<=0 ? 'Marcar todo' : 'Desmarcar todos'}', style: TextStyle(color: colors['primary'])),
                    Icon(bloc.equipmentExerciseValue.length<=0 ? MyFlutterApp.ok : MyFlutterApp.cross, color: colors['primary'],size: 15.0)
                  ],
                  spacing: 5,
                  runSpacing: 5,
                  alignment: WrapAlignment.center
                ),
                onClick: () {
                  if (bloc.equipmentExerciseValue.length>0) {
                    bloc.equipmentExerciseSet([]);
                  } else {
                    bloc.equipmentExerciseSet(["Barbell","Barbell plate","Parallettes/Parallel bars","Bench","Racks","Dumbbell","Battle rope","Bicycle","Box jumps","Climbing rope","Dips","GHD","Gymnastic rings","Pull-up bar","Hammer","Kettlebell","Log","Medicine Ball","Rower","SandBag","Skipping rope","Sled","Stone","Swimming Pool","Tire","Vest"]);
                  }
                  //Navigator.pushNamed(context, 'training-workout-detail', arguments: tw);
                }
              ),
              colors: generateGradient(235, 235, 235),
              borderRadius: BorderRadius.circular(30),
            )
          ],
        ),
        SizedBox(height: 20.0,),
        Wrap(
          spacing: 20.0,
          runSpacing: 20.0,
          crossAxisAlignment: WrapCrossAlignment.center,
          alignment: WrapAlignment.spaceBetween,
          children: <Widget>[
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Barbell",
                "Barbell",
                Icon(MyFlutterApp.barbell, size: 30.0, color: equipment_exercise.contains("Barbell") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Platos",
                "Barbell plate",
                Icon(MyFlutterApp.barbellplate, size: 30.0, color: equipment_exercise.contains("Barbell plate") ? colors['primary'] : Color(0xFF575F6B)))
              
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Paralelas",
                "Parallettes/Parallel bars",
                Icon(MyFlutterApp.parallettes, size: 30.0, color: equipment_exercise.contains("Parallettes/Parallel bars") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Rack",
                "Racks",
                Icon(MyFlutterApp.racks, size: 30.0, color: equipment_exercise.contains("Racks") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Press de Banca",
                "Bench",
                Icon(MyFlutterApp.bench_press, size: 30.0, color: equipment_exercise.contains("Bench") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Dumbbell",
                "Dumbbell",
                Container(width: 30.0,height: 30.0,child: Icon(MyFlutterApp.dumbbell, size: 20.0, color: equipment_exercise.contains("Dumbbell") ? colors['primary'] : Color(0xFF575F6B))))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Battle Rope",
                "Battle rope",
                Icon(MyFlutterApp.battlerope, size: 30.0, color: equipment_exercise.contains("Battle rope") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Assault Bike",
                "Bicycle",
                Icon(MyFlutterApp.assaultbike, size: 30.0, color: equipment_exercise.contains("Bicycle") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Cajón",
                "Box jumps",
                Icon(MyFlutterApp.boxjump, size: 30.0, color: equipment_exercise.contains("Box jumps") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Rack Dips",
                "Dips",
                Icon(MyFlutterApp.dips, size: 30.0, color: equipment_exercise.contains("Dips") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Cuerdad de escalada",
                "Climbing rope",
                Icon(MyFlutterApp.climbingrope, size: 30.0, color: equipment_exercise.contains("Climbing rope") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"GHD",
                "GHD",
                Icon(MyFlutterApp.ghd, size: 30.0, color: equipment_exercise.contains("GHD") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Rings",
                "Gymnastic rings",
                Icon(MyFlutterApp.rings, size: 30.0, color: equipment_exercise.contains("Gymnastic rings") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Pull-up bar",
                "Pull-up bar",
                Icon(MyFlutterApp.dominadas, size: 30.0, color: equipment_exercise.contains("Pull-up bar") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Hammer",
                "Hammer",
                Icon(MyFlutterApp.hammer, size: 30.0, color: equipment_exercise.contains("Hammer") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Kettlebell",
                "Kettlebell",
                Icon(MyFlutterApp.kettlebell, size: 30.0, color: equipment_exercise.contains("Kettlebell") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Medicine ball",
                "Medicine Ball",
                Icon(MyFlutterApp.medicineball, size: 30.0, color: equipment_exercise.contains("Medicine Ball") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Remo",
                "Rower",
                Icon(MyFlutterApp.rower, size: 30.0, color: equipment_exercise.contains("Rower") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"SandBag",
                "SandBag",
                Icon(MyFlutterApp.sandbag, size: 30.0, color: equipment_exercise.contains("SandBag") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Cuerda",
                "Skipping rope",
                Icon(MyFlutterApp.rope, size: 30.0, color: equipment_exercise.contains("Skipping rope") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Trineo",
                "Sled",
                Icon(MyFlutterApp.sled, size: 30.0, color: equipment_exercise.contains("Sled") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Piedra",
                "Stone",
                Icon(MyFlutterApp.stone, size: 30.0, color: equipment_exercise.contains("Stone") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Piscina",
                "Swimming Pool",
                Icon(MyFlutterApp.swimmingpool, size: 30.0, color: equipment_exercise.contains("Swimming Pool") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Rueda",
                "Tire",
                Icon(MyFlutterApp.tire, size: 30.0, color: equipment_exercise.contains("Tire") ? colors['primary'] : Color(0xFF575F6B)))
            ),
            Container (
              width: 90,
              height: 90,
              child: _buttonMaterial(context, bloc,equipment_exercise,"Chaleco",
                "Vest",
                Icon(MyFlutterApp.vest, size: 30.0, color: equipment_exercise.contains("Vest") ? colors['primary'] : Color(0xFF575F6B)))
            ),
          ],
        ),
      ],
    );
  }
}