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: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';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.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
  late 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 as LinkedHashMap;
    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_black_background.jpg')
                  : AssetImage('asset/image/WT_light_background.jpg'),
              fit: BoxFit.cover,
              alignment: Alignment.center,
            ),
          ),
          child: BlocConsumer<ExercisePlanBloc, ExercisePlanState>(listener: (context, state) {
            if (state is ExercisePlanError) {
              ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                content: Text(
                  state.message,
                ),
                backgroundColor: Colors.orange,
              ));
            }
          }, builder: (context, state) {
            return ModalProgressHUD(
              child: exerciseWidget(bloc),
              inAsyncCall: state is ExercisePlanLoading,
              opacity: 0.5,
              color: Colors.black54,
              progressIndicator: CircularProgressIndicator(),
            );
          })),
      bottomNavigationBar: BottomNavigator(bottomNavIndex: 2),
    );
  }

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

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

    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: GoogleFonts.archivoBlack(fontSize: 20),
                    ),
                  ],
                ),
                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: GoogleFonts.inter(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: false,
            parent: TreeviewParentWidget(text: name),
            children: _getChildList(list, bloc),
          )));
    });

    return exerciseTypes;
  }

  List<Widget> _getChildList(List<WorkoutMenuTree> listWorkoutTree, ExercisePlanBloc bloc) {
    List<Widget> list = [];
    listWorkoutTree.forEach((element) {
      final String unitQuantityUnit =
          element.exerciseType != null && element.exerciseType!.unitQuantityUnit != null ? element.exerciseType!.unitQuantityUnit! : "";
      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.green[300],
                          )
                        : Icon(
                            Icons.add,
                            color: Colors.indigo,
                          ),
                    onPressed: () => clickAddDetail(bloc, element),
                  ),
                  SizedBox(width: 10),
                  Flexible(
                    fit: FlexFit.tight,
                    flex: 8,
                    child: InkWell(
                      child: Text(
                        element.name,
                        textAlign: TextAlign.start,
                        style: GoogleFonts.inter(fontSize: 16, 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! +
                                unitQuantityUnit,
                            style: TextStyle(fontSize: 9, color: Colors.green),
                          ),
                    onTap: () => clickAddDetail(bloc, element),
                  ),
                ]),
              )),
          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);
  }
}
