import 'dart:collection';

import 'package:aitrainer_app/bloc/exercise_plan/exercise_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: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 ExercisePlanCustomPage extends StatefulWidget {
  @override
  _ExercisePlanCustomPage createState() => _ExercisePlanCustomPage();
}

class _ExercisePlanCustomPage extends State<ExercisePlanCustomPage> with Trans {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  // ignore: close_sinks
  ExercisePlanBloc bloc;

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

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

  @override
  Widget build(BuildContext context) {
    LinkedHashMap arguments = ModalRoute.of(context).settings.arguments;
    final int customerId = arguments['customerId'];
    bloc = BlocProvider.of<ExercisePlanBloc>(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_menu_dark.png'):
                AssetImage('asset/image/WT_menu_dark.png'),
                fit: BoxFit.cover,
                alignment: Alignment.center,
              ),
            ),
            child: BlocConsumer<ExercisePlanBloc, ExercisePlanState>(
              listener: (context, state) {
                if (state is ExercisePlanError) {
                  Scaffold.of(context).showSnackBar(SnackBar(
                    content: Text(
                      state.message,
                    ),
                    backgroundColor: Colors.orange,
                  ));
                } else if (state is ExercisePlanLoading) {
                  LoadingDialog();
                }
              },
                // ignore: missing_return
              builder: (context, state) {
                if (state is ExercisePlanReady) {
                  return exerciseWidget(bloc);
                }
                return Container();

            }
            )
        ),
      bottomNavigationBar: BottomNavigator(bottomNavIndex: 2),
    );
  }

  Widget exerciseWidget(ExercisePlanBloc bloc) {
    return TreeView(
      startExpanded: false,
      children: _getTreeChildren(bloc),
    );
  }

  List<Widget> _getTreeChildren(ExercisePlanBloc bloc) {
    List<Widget> exerciseTypes = List();

    Card explanation = Card(
      color: Colors.white60,
      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("  "),
                Text(
                  t("Custom Exercise Plan"),
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
              ],
            ),
            Divider(
              color: Colors.transparent,
            ),
            Text(
              t("Select manually the exercises what you would like to have in your plan. At the end don't forget to save."),
              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, ExercisePlanBloc bloc) {
    List<Widget> list = List();
    listWorkoutTree.forEach((element) {

        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.selected ? Icon(Icons.check, color: Colors.greenAccent.shade700,)
                        : Icon(Icons.add, color: Colors.blue.shade400,),
                      onPressed: () => clickAddDetail(bloc, element),
                    ),
                    SizedBox(width: 10),
                    Flexible(
                      fit: FlexFit.tight,
                      flex: 8,
                      child:
                      InkWell(
                        child:
                        Text(
                          element.name,
                          textAlign: TextAlign.start,
                          style: TextStyle(fontSize: 12, color: Colors.black),
                        ),
                        onTap: () => clickAddDetail(bloc, element),
                      ),
                    ),
                    InkWell(
                      child:
                        !element.selected || bloc.exercisePlanRepository.exercisePlanDetails[element.exerciseTypeId] == null ||
                          bloc.exercisePlanRepository.exercisePlanDetails[element.exerciseTypeId].change == null ? Text("") :
                      Text(bloc.exercisePlanRepository.exercisePlanDetails[element.exerciseTypeId].repeats.toString() +
                      " x " + bloc.exercisePlanRepository.exercisePlanDetails[element.exerciseTypeId].weightEquation +
                     " " + element.exerciseType.unitQuantityUnit, style: TextStyle(fontSize: 9, color: Colors.green),),
                      onTap: () => clickAddDetail(bloc, element),
                    ),
                    IconButton(

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

                      },
                    ),

                  ]),
              )
            ),
            children: [
            ]
          )
        );

    });
    return list;
  }

  void clickAddDetail(ExercisePlanBloc bloc, WorkoutMenuTree workoutMenuTree) {
    final LinkedHashMap args = LinkedHashMap();
    args['bloc'] = bloc;
    args['workoutTreeItem'] = workoutMenuTree;
    Navigator.of(context).pushNamed("exercisePlanDetailAdd", arguments: args);
  }
}