import 'dart:async';
import 'dart:collection';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar.dart';
import 'package:aitrainer_app/widgets/dialog_premium.dart';
import 'package:aitrainer_app/widgets/treeview_parent_widget.dart';
import 'package:aitrainer_app/util/common.dart';
import 'package:aitrainer_app/bloc/development_by_muscle/development_by_muscle_bloc.dart';
import 'package:aitrainer_app/model/workout_menu_tree.dart';
import 'package:aitrainer_app/library/tree_view.dart';
import 'package:aitrainer_app/widgets/bottom_nav.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class MyDevelopmentMusclePage extends StatefulWidget {
  @override
  _MyDevelopmentMuscleState createState() => _MyDevelopmentMuscleState();
}

class _MyDevelopmentMuscleState extends State<MyDevelopmentMusclePage> with Common, Trans {
  late DevelopmentByMuscleBloc bloc;
  late double cWidth;

  @override
  void initState() {
    super.initState();
    if (!Cache().hasPurchased && Cache().userLoggedIn != null) {
      Timer(
          Duration(milliseconds: 2000),
          () => {
                showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (BuildContext context) {
                      return DialogPremium(
                        unlocked: false,
                        unlockRound: 1,
                        function: "Development Of Muscles",
                        unlockedText: "",
                        onTap: () => {Navigator.of(context).pop(), Navigator.of(context).pop()},
                        onCancel: () => {Navigator.of(context).pop(), Navigator.of(context).pop()},
                      );
                    })
              });
    }

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

  @override
  Widget build(BuildContext context) {
    bloc = BlocProvider.of<DevelopmentByMuscleBloc>(context);
    cWidth = mediaSizeWidth(context);
    setContext(context);

    return Scaffold(
      appBar: AppBarNav(depth: 1),
      body: Container(
        padding: EdgeInsets.all(20),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('asset/image/WT_menu_dark.jpg'),
            fit: BoxFit.cover,
            alignment: Alignment.center,
          ),
        ),
        child: BlocConsumer<DevelopmentByMuscleBloc, DevelopmentByMuscleState>(
          listener: (context, state) {
            if (state is DevelopmentByMuscleErrorState) {
              ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                content: Text(
                  state.message,
                ),
                backgroundColor: Colors.orange,
              ));
            }
          },
          builder: (context, state) {
            if (state is DevelopmentByMuscleStateInitial) {
              return Container();
            } else {
              return TreeView(
                startExpanded: false,
                children: _getTreeChildren(bloc),
              );
            }
          },
        ),
      ),
      bottomNavigationBar: BottomNavigator(bottomNavIndex: 1),
    );
  }

  Card getExplanation(DevelopmentByMuscleBloc bloc) {
    Card explanation = Card(
        color: Colors.white60,
        child: Container(
            padding: EdgeInsets.only(left: 10, right: 5, top: 12),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Row(
                  children: [
                    Icon(
                      Icons.info,
                      color: Colors.orangeAccent,
                    ),
                    Text("  "),
                    Text(
                      t("My Development By Muscle"),
                      style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                Divider(
                  color: Colors.transparent,
                ),
                Text(
                  t("Here you see you development in the last period."),
                  style: TextStyle(fontSize: 12, fontWeight: FontWeight.normal),
                ),
              ],
            )));
    return explanation;
  }

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

    Card explanation = this.getExplanation(bloc);
    exerciseTypes.add(explanation);

    LinkedHashMap<String, dynamic> rc = LinkedHashMap();
    bloc.workoutTreeRepository.sortedTree.forEach((name, list) {
      rc = _getChildList(list, bloc);
      final List<Widget> children = rc['list'];
      final bool hasNoData = rc['hasNoData'];
      exerciseTypes.add(Container(
          margin: const EdgeInsets.only(left: 8.0),
          child: TreeViewChild(
            startExpanded: false,
            parent: _getExerciseGroupWidget(exerciseTypeName: name, noData: hasNoData),
            children: children,
          )));
    });

    return exerciseTypes;
  }

  Widget _getExerciseGroupWidget({required String exerciseTypeName, bool noData = false}) {
    return TreeviewParentWidget(
      text: exerciseTypeName,
      backgroundColor: !noData ? Colors.white38 : Colors.white12,
      color: !noData ? Colors.blue[800] : Colors.blue[100],
    );
  }

  Widget _getExerciseWidget({required String exerciseTypeName, bool noData = false}) {
    return TreeviewParentWidget(
      text: exerciseTypeName,
      backgroundColor: !noData ? Colors.white38 : Colors.white12,
      color: !noData ? Colors.blue[700] : Colors.blue[100],
      fontSize: 16,
    );
  }

  LinkedHashMap<String, dynamic> _getChildList(List<WorkoutMenuTree> listWorkoutTree, DevelopmentByMuscleBloc bloc) {
    LinkedHashMap<String, dynamic> rc = LinkedHashMap();
    List<Widget> list = [];
    rc['list'] = list;
    rc['hasNoData'] = false;
    listWorkoutTree.forEach((element) {
      list.add(Container(
          margin: const EdgeInsets.only(left: 8.0),
          child: TreeViewChild(
            parent: _getExerciseWidget(exerciseTypeName: element.exerciseType!.nameTranslation),
            children: [],
            onTap: () => onPressed(bloc, element),
          )));
    });

    return rc;
  }

  void onPressed(DevelopmentByMuscleBloc bloc, WorkoutMenuTree element) {
    HashMap<String, dynamic> args = HashMap();
    args['exerciseRepository'] = bloc.exerciseRepository;
    args['workoutTreeRepository'] = bloc.workoutTreeRepository;
    args['exerciseTypeId'] = element.exerciseTypeId;
    args['title'] = t("Muscle development") + ": " + "${element.exerciseType!.nameTranslation}";
    Navigator.of(context).pushNamed('developmentDiagramPage', arguments: args);
  }
}
