import 'dart:collection';
import 'package:aitrainer_app/bloc/exercise_execute_plan/exercise_execute_plan_bloc.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/workout_menu_tree.dart';
import 'package:aitrainer_app/library/tree_view.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar.dart';
import 'package:aitrainer_app/widgets/bottom_nav.dart';
import 'package:aitrainer_app/widgets/treeview_parent_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';

class ExerciseExecutePage extends StatefulWidget {
  @override
  _ExerciseExecutePage createState() => _ExerciseExecutePage();
}

class _ExerciseExecutePage extends State<ExerciseExecutePage> with Trans {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  // ignore: close_sinks
  late ExerciseExecutePlanBloc bloc;

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

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

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

    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBarNav(depth: 1),
      body: Container(
          padding: EdgeInsets.all(20),
          decoration: BoxDecoration(
            image: DecorationImage(
              image: customerId == Cache().userLoggedIn!.customerId
                  ? AssetImage('asset/image/WT_black_background.jpg')
                  : AssetImage('asset/image/WT_light_background.jpg'),
              fit: BoxFit.cover,
              alignment: Alignment.center,
            ),
          ),
          child: BlocConsumer<ExerciseExecutePlanBloc, ExerciseExecutePlanState>(listener: (context, state) {
            if (state is ExerciseByPlanError) {
              //LoadingDialog.hide(context);
              ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                content: Text(
                  state.message,
                ),
                backgroundColor: Colors.orange,
              ));
            } else if (state is ExerciseByPlanLoading) {
              //LoadingDialog.show(context);
            }
          }, builder: (context, state) {
            if (state is ExerciseByPlanStateInitial || state is ExerciseByPlanLoading) {
              return Container();
            } else if (state is ExerciseByPlanReady) {
              //LoadingDialog.hide(context);
              return exerciseWidget(bloc);
            } else {
              return exerciseWidget(bloc);
            }
          })),
      bottomNavigationBar: BottomNavigator(bottomNavIndex: 2),
    );
  }

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

  List<Widget> nodeExercisePlan(ExerciseExecutePlanBloc bloc) {
    List<Widget> exerciseTypes = [];
    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: GoogleFonts.archivoBlack(
                          fontSize: 20,
                        ),
                        maxLines: 2,
                      ),
                    ),
                  ],
                ),
                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);

    if (bloc.selectedNumber == 0) {
      exerciseTypes.add(Container(
          child: Center(
              child: Text(
        t("Please define your Exercise Plan"),
        style: GoogleFonts.inter(color: Colors.white),
      ))));
      exerciseTypes.add(Container(
          child: Center(
              child: Text(
        t("Go to: 'Training Plan' - 'Edit My Custom Plan'"),
        style: GoogleFonts.inter(color: Colors.white),
      ))));
      exerciseTypes.add(Container(
          child: Center(
              child: InkWell(
                  onTap: () {
                    final LinkedHashMap args = LinkedHashMap();
                    args['customerId'] = Cache().userLoggedIn!.customerId;
                    Navigator.of(context).pop();
                    Navigator.of(context).pushNamed('exercisePlanCustomPage', arguments: args);
                  },
                  child: Text(
                    t("Jump there »"),
                    style: GoogleFonts.inter(color: Colors.blue[200], decorationStyle: TextDecorationStyle.solid),
                  )))));
    } else {
      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, ExerciseExecutePlanBloc bloc) {
    List<Widget> 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[200])
                          : Icon(
                              Icons.indeterminate_check_box,
                              color: Colors.blue.shade800,
                            ),
                      onPressed: () => {addExerciseByPlanEvent(bloc, element)},
                    ),
                    SizedBox(width: 20),
                    Flexible(
                      fit: FlexFit.tight,
                      child: InkWell(
                        child: Text(
                          element.name,
                          textAlign: TextAlign.start,
                          style: GoogleFonts.inter(fontSize: 17, color: Colors.black),
                        ),
                        onTap: () => {addExerciseByPlanEvent(bloc, element)},
                      ),
                    ),
                    IconButton(
                      padding: EdgeInsets.all(0),
                      icon: Icon(
                        Icons.info,
                        color: Colors.black12,
                      ),
                      onPressed: () {},
                    ),
                  ]),
                )),
            children: []));
      }
    });
    return list;
  }

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