import 'dart:collection';
import 'package:aitrainer_app/bloc/exercise_by_plan/exercise_by_plan_bloc.dart';
import 'package:aitrainer_app/localization/app_language.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/workout_menu_tree.dart';
import 'package:aitrainer_app/treeview/tree_view.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar_common.dart';
import 'package:aitrainer_app/widgets/bottom_nav.dart';
import 'package:aitrainer_app/widgets/treeview_parent_widget.dart';
import 'package:aitrainer_app/widgets/splash.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class ExerciseByPlanPage extends StatefulWidget {
  @override
  _ExerciseByPlanPage createState() => _ExerciseByPlanPage();
}

class _ExerciseByPlanPage extends State<ExerciseByPlanPage> with Trans {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  // ignore: close_sinks
  ExerciseByPlanBloc bloc;

  @override
  void initState() {
    super.initState();

    /// We require the initializers to run after the loading screen is rendered
    SchedulerBinding.instance.addPostFrameCallback((_) {
      BlocProvider.of<ExerciseByPlanBloc>(context).add(ExerciseByPlanLoad());
    });
  }

  @override
  Widget build(BuildContext context) {
    LinkedHashMap arguments = ModalRoute.of(context).settings.arguments;
    final int customerId = arguments['customerId'];
    bloc = BlocProvider.of<ExerciseByPlanBloc>(context);
    bloc.customerId = customerId;
    setContext(context);

    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBarCommonNav(),
      body: Container(
          padding: EdgeInsets.all(20),
          decoration: BoxDecoration(
            image: DecorationImage(
              image: customerId == Cache().userLoggedIn.customerId
                  ? AssetImage('asset/image/WT_light_background.png')
                  : AssetImage('asset/image/WT_menu_dark.png'),
              fit: BoxFit.cover,
              alignment: Alignment.center,
            ),
          ),
          child: BlocConsumer<ExerciseByPlanBloc, ExerciseByPlanState>(
            listener: (context, state) {
              if (state is ExerciseByPlanError) {
                Scaffold.of(context).showSnackBar(SnackBar(
                  content: Text(
                    state.message,
                  ),
                  backgroundColor: Colors.orange,
                ));
              } else if (state is ExerciseByPlanLoading) {
                LoadingDialog();
              }
            },

            builder: (context, state) {
              if (state is ExerciseByPlanStateInitial || state is ExerciseByPlanLoading) {
                return Container();
              } else if (state is ExerciseByPlanReady) {
                return exerciseWidget(bloc);
              } else {
                return exerciseWidget(bloc);
              }
          })),
      bottomNavigationBar: BottomNavigator(bottomNavIndex: 2),
    );
  }

  Widget exerciseWidget(ExerciseByPlanBloc bloc) {
    return TreeView(
      startExpanded: false,
      children: nodeExercisePlan(bloc),
    );
  }

  List<Widget> nodeExercisePlan(ExerciseByPlanBloc bloc) {
    List<Widget> exerciseTypes = List();
    bool isEnglish = AppLanguage().appLocal == Locale("en");

    Card explanation = Card(
        color: Colors.white38,
        child: Container(
            padding: EdgeInsets.only(left: 10, right: 5, top: 12, bottom: 8),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Row(
                  children: [
                    Icon(
                      Icons.info,
                      color: Colors.orangeAccent,
                    ),
                    Text("  "),
                    Flexible(
                      child:
                      Text(
                        t("Execute your active Exercise Plan!"),
                        style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                      ),
                      ),

                  ],
                ),
                Divider(
                  color: Colors.transparent,
                ),
                Text(
                  t("Select the muscle type and tap on the exercise. One the next page enter the weight and repeat."),
                  style: TextStyle(fontSize: 12, fontWeight: FontWeight.normal),
                ),
              ],
            )));

    exerciseTypes.add(explanation);

    bloc.menuTreeRepository.sortedTree.forEach((name, list) {
      exerciseTypes.add(
        Container(
          margin: const EdgeInsets.only(left: 4.0),
          child: TreeViewChild(
            startExpanded: true,
            parent: TreeviewParentWidget(text: name),
            children: _getChildList(list, bloc),
          )));
    });

    return exerciseTypes;
  }

  List<Widget> _getChildList(List<WorkoutMenuTree> listWorkoutTree, ExerciseByPlanBloc bloc) {
    List<Widget> list = List();
    listWorkoutTree.forEach((element) {

      if ( element.selected) {
        list.add(
          TreeViewChild(
            startExpanded: false,
            parent:
              Card(
                margin: EdgeInsets.only(left: 10, top: 5),
                color: Colors.white54,
                child: Container(
                  padding: const EdgeInsets.only(left: 5, top: 0, right: 5, bottom: 0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      IconButton(
                        icon: element.executed ? Icon(Icons.check_box, color: Colors.green):
                          Icon(Icons.indeterminate_check_box, color: Colors.blue.shade800,),
                        onPressed: () => {
                          addExerciseByPlanEvent(bloc, element)
                        },
                      ),
                      SizedBox(width: 20),
                      Flexible(
                        child:
                        InkWell(
                          child:
                          Text(
                            element.name,
                            textAlign: TextAlign.start,
                            style: TextStyle(fontSize: 12, color: Colors.black),
                          ),
                          onTap: () => {
                            addExerciseByPlanEvent(bloc, element)
                          },
                        ),

                      ),
                      IconButton(

                        padding: EdgeInsets.all(0),
                        icon: Icon(Icons.description, color: Colors.black12,),
                        onPressed: () {

                        },
                      ),

                    ]),
                )
              ),
            children: [
            ]
        )
        );
      }
    });
    return list;
  }

  void addExerciseByPlanEvent(ExerciseByPlanBloc bloc, WorkoutMenuTree workoutTree) {
    LinkedHashMap args = LinkedHashMap();
    args['blocExerciseByPlan'] = bloc;
    args['customerId'] = bloc.customerId;
    args['workoutTree'] = workoutTree;
    Navigator.of(context).pushNamed("exerciseAddByPlanPage", arguments: args);
  }
}