import 'dart:collection';
import 'dart:ui';

import 'package:aitrainer_app/bloc/result/result_bloc.dart';
import 'package:aitrainer_app/localization/app_language.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/exercise_ability.dart';
import 'package:aitrainer_app/repository/exercise_repository.dart';
import 'package:aitrainer_app/repository/exercise_result_repository.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar_min.dart';
import 'package:aitrainer_app/widgets/bottom_nav.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_bloc/flutter_form_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:aitrainer_app/model/result.dart';

// ignore: must_be_immutable
class EvaluationPage extends StatelessWidget with Trans {
  @override
  Widget build(BuildContext context) {
    LinkedHashMap arguments = ModalRoute.of(context).settings.arguments;
    ExerciseRepository exerciseRepository;
    // ignore: close_sinks
    if (arguments != null) {
      exerciseRepository = arguments['exerciseRepository'];
    } else {
      exerciseRepository = ExerciseRepository();
    }
    ResultType resultType = ResultType.none;
    String imageUrl = "";
    if (Cache().userLoggedIn.sex == "m") {
      resultType = ResultType.man;
      imageUrl = 'asset/image/WT_Results_for_men.png';
    } else {
      resultType = ResultType.man;
      imageUrl = 'asset/image/WT_Results_for_female.png';
    }
    if (exerciseRepository.exerciseType.getAbility().equalsTo(ExerciseAbility.running)) {
      resultType = ResultType.running;
      imageUrl = 'asset/image/WT_Results_for_runners.png';
    }
    setContext(context);
    return Scaffold(
        appBar: AppBarMin(
          back: true,
        ),
        body: Container(
            height: double.infinity,
            width: double.infinity,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(imageUrl),
                fit: BoxFit.cover,
                alignment: Alignment.topCenter,
              ),
            ),
            child: BlocProvider(
                create: (context) =>
                    ResultBloc(resultRepository: ExerciseResultRepository(resultType: resultType), exerciseRepository: exerciseRepository)
                      ..add(ResultLoad()),
                child: BlocConsumer<ResultBloc, ResultState>(listener: (context, state) {
                  if (state is ResultError) {
                    Scaffold.of(context).showSnackBar(
                        SnackBar(backgroundColor: Colors.orange, content: Text(state.error, style: TextStyle(color: Colors.white))));
                  } else if (state is ResultLoading) {
                    Scaffold.of(context).showSnackBar(SnackBar(
                        duration: Duration(milliseconds: 100),
                        backgroundColor: Colors.transparent,
                        content: Container(child: Center(child: CircularProgressIndicator()))));
                  }
                }, builder: (context, state) {
                  final resultBloc = BlocProvider.of<ResultBloc>(context);
                  return getEvaluationWidgets(resultBloc);
                }))),
        bottomNavigationBar: BottomNavigator(bottomNavIndex: 0));
  }

  Widget getEvaluationWidgets(ResultBloc resultBloc) {
    String exerciseName = AppLanguage().appLocal == Locale("en")
        ? resultBloc.exerciseRepository.exerciseType.name
        : resultBloc.exerciseRepository.exerciseType.nameTranslation;
    return Container(
        padding: EdgeInsets.only(left: 10, right: 10),
        child: CustomScrollView(scrollDirection: Axis.vertical, slivers: [
          SliverAppBar(
            pinned: true,
            backgroundColor: Colors.transparent,
            expandedHeight: 50.0,
            automaticallyImplyLeading: false,
            flexibleSpace: FlexibleSpaceBar(
              title: Text(exerciseName,
                  textAlign: TextAlign.center,
                  maxLines: 3,
                  softWrap: true,
                  style: GoogleFonts.archivoBlack(
                    fontSize: 24,
                    color: Colors.white,
                    shadows: <Shadow>[
                      Shadow(
                        offset: Offset(5.0, 5.0),
                        blurRadius: 12.0,
                        color: Colors.black54,
                      ),
                      Shadow(
                        offset: Offset(-3.0, 3.0),
                        blurRadius: 12.0,
                        color: Colors.black54,
                      ),
                    ],
                  )),
            ),
          ),
          SliverList(
            delegate: SliverChildListDelegate([
              Text(DateFormat('y-M-d HH:mm', AppLanguage().appLocal.toString()).format(resultBloc.exerciseRepository.start),
                  textAlign: TextAlign.center,
                  maxLines: 2,
                  softWrap: true,
                  style: GoogleFonts.archivoBlack(
                    fontSize: 20,
                    color: Colors.white,
                    shadows: <Shadow>[
                      Shadow(
                        offset: Offset(5.0, 5.0),
                        blurRadius: 12.0,
                        color: Colors.black54,
                      ),
                      Shadow(
                        offset: Offset(-3.0, 3.0),
                        blurRadius: 12.0,
                        color: Colors.black54,
                      ),
                    ],
                  )),
              Divider(color: Colors.transparent),
              Divider(color: Colors.transparent),
              Text(t("Summary of your test"),
                  textAlign: TextAlign.center,
                  maxLines: 2,
                  softWrap: true,
                  style: GoogleFonts.archivoBlack(
                    fontSize: 20,
                    color: Colors.yellow[300],
                    shadows: <Shadow>[
                      Shadow(
                        offset: Offset(5.0, 5.0),
                        blurRadius: 12.0,
                        color: Colors.black54,
                      ),
                      Shadow(
                        offset: Offset(-3.0, 3.0),
                        blurRadius: 12.0,
                        color: Colors.black54,
                      ),
                    ],
                  )),
            ]),
          ),
          getResultSummary(resultBloc),
          getSuggestionTitle(resultBloc),
          getSuggestion(resultBloc),
          emptySliver(),
          getResultTitle(resultBloc),
          getResults(resultBloc),
        ]));
  }

  Widget getSuggestionTitle(ResultBloc resultBloc) {
    if (resultBloc.exerciseRepository.exerciseType.unitQuantityUnit != null) {
      return SliverList(
        delegate: SliverChildListDelegate(
          [
            Divider(color: Colors.transparent),
            Divider(color: Colors.transparent),
            Text(t("Suggestions based on your test"),
                textAlign: TextAlign.center,
                maxLines: 2,
                softWrap: true,
                style: GoogleFonts.archivoBlack(
                  fontSize: 20,
                  color: Colors.yellow[300],
                  shadows: <Shadow>[
                    Shadow(
                      offset: Offset(5.0, 5.0),
                      blurRadius: 12.0,
                      color: Colors.black54,
                    ),
                    Shadow(
                      offset: Offset(-3.0, 3.0),
                      blurRadius: 12.0,
                      color: Colors.black54,
                    ),
                  ],
                )),
          ],
        ),
      );
    } else
      return emptySliver();
  }

  Widget getResultTitle(ResultBloc resultBloc) {
    return SliverList(
      delegate: SliverChildListDelegate(
        [
          Divider(color: Colors.transparent),
          Divider(color: Colors.transparent),
          Text(t("Health Data Summary"),
              textAlign: TextAlign.center,
              maxLines: 2,
              softWrap: true,
              style: GoogleFonts.archivoBlack(
                fontSize: 20,
                color: Colors.yellow[300],
                shadows: <Shadow>[
                  Shadow(
                    offset: Offset(5.0, 5.0),
                    blurRadius: 12.0,
                    color: Colors.black54,
                  ),
                  Shadow(
                    offset: Offset(-3.0, 3.0),
                    blurRadius: 12.0,
                    color: Colors.black54,
                  ),
                ],
              )),
          Divider(),
        ],
      ),
    );
  }

  Widget getSuggestion(ResultBloc resultBloc) {
    if (resultBloc.exerciseRepository.exerciseType.unitQuantityUnit != null) {
      return SliverList(
        delegate: SliverChildListDelegate(
          [
            getSuggestionWidget(resultBloc, "Hypertrophy", "asset/image/pict_hypertrophy.png", "3x10-12", 0.9, "2"),
            Divider(color: Colors.transparent),
            getSuggestionWidget(resultBloc, "Gain Strength", "asset/image/pict_weight_volumen_tonna.png", "3x10-12", 0.75, "3-5"),
            Divider(color: Colors.transparent),
            getSuggestionWidget(resultBloc, "Endurance", "asset/image/pict_reps_volumen_db.png", "4x25-35", 0.50, "3"),
          ],
        ),
      );
    } else
      return emptySliver();
  }

  Widget emptySliver({int count = 1}) {
    return SliverList(
      delegate: SliverChildListDelegate(
        [
          Container(),
          Divider(color: Colors.transparent),
        ],
      ),
    );
  }

  Widget getSuggestionWidget(ResultBloc resultBloc, String title, String picture, String repeats, double percent, String restTime) {
    String unitQuantityUnit = resultBloc.exerciseRepository.exerciseType.unitQuantityUnit == null
        ? ""
        : resultBloc.exerciseRepository.exerciseType.unitQuantityUnit;
    return Column(
      children: [
        Text(t(title),
            textAlign: TextAlign.center,
            maxLines: 2,
            softWrap: true,
            style: GoogleFonts.archivoBlack(
              fontSize: 30,
              color: Colors.white,
              shadows: <Shadow>[
                Shadow(
                  offset: Offset(5.0, 5.0),
                  blurRadius: 12.0,
                  color: Colors.black54,
                ),
                Shadow(
                  offset: Offset(-3.0, 3.0),
                  blurRadius: 12.0,
                  color: Colors.black54,
                ),
              ],
            )),
        Row(children: [
          Image.asset(
            picture,
            height: 80,
          ),
          SizedBox(
            width: 10,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(repeats + " " + t("repeats"),
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      softWrap: true,
                      style: GoogleFonts.archivoBlack(
                        fontSize: 18,
                        color: Colors.orange,
                        shadows: <Shadow>[
                          Shadow(
                            offset: Offset(5.0, 5.0),
                            blurRadius: 12.0,
                            color: Colors.black54,
                          ),
                          Shadow(
                            offset: Offset(-3.0, 3.0),
                            blurRadius: 12.0,
                            color: Colors.black54,
                          ),
                        ],
                      ))
                ],
              ),
              Row(
                children: [
                  Text(t("Weight") + ": " + resultBloc.calculate1RM(percent: percent).toStringAsFixed(0) + " " + unitQuantityUnit,
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      softWrap: true,
                      style: GoogleFonts.archivoBlack(
                        fontSize: 18,
                        color: Colors.orange,
                        shadows: <Shadow>[
                          Shadow(
                            offset: Offset(5.0, 5.0),
                            blurRadius: 12.0,
                            color: Colors.black54,
                          ),
                          Shadow(
                            offset: Offset(-3.0, 3.0),
                            blurRadius: 12.0,
                            color: Colors.black54,
                          ),
                        ],
                      )),
                ],
              ),
              Row(
                children: [
                  Text(t("Rest time") + ": " + restTime + " " + t("minutes"),
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      softWrap: true,
                      style: GoogleFonts.archivoBlack(
                        fontSize: 18,
                        color: Colors.orange,
                        shadows: <Shadow>[
                          Shadow(
                            offset: Offset(5.0, 5.0),
                            blurRadius: 12.0,
                            color: Colors.black54,
                          ),
                          Shadow(
                            offset: Offset(-3.0, 3.0),
                            blurRadius: 12.0,
                            color: Colors.black54,
                          ),
                        ],
                      )),
                ],
              ),
            ],
          )
        ]),
      ],
    );
  }

  Widget getSummary(ResultBloc bloc) {
    int index = 0;
    List<Text> resultList = List();
    bloc.exerciseRepository.actualExerciseList.forEach((exercise) {
      final String unit = t(bloc.exerciseRepository.exerciseType.unit);
      String exerciseElement = "";
      final String exerciseRepeats = exercise.quantity.toStringAsFixed(0);
      final String exerciseUnitQuantity = exercise.unitQuantity != null ? "x" + exercise.unitQuantity.toStringAsFixed(0) : "";
      if (index == 0) {
        exerciseElement = t("Test") + ": ";
      } else if (index == 1) {
        exerciseElement = t("1st Control") + ": ";
      } else if (index == 2) {
        exerciseElement = t("2nd Control") + ": ";
      } else if (index == 3) {
        exerciseElement = t("3rd Control") + ": ";
      }
      index++;
      resultList.add(
        Text(exerciseElement + exerciseRepeats + exerciseUnitQuantity + " " + unit,
            textAlign: TextAlign.center,
            maxLines: 2,
            softWrap: true,
            style: GoogleFonts.inter(
              fontSize: 18,
              color: Colors.white,
              shadows: <Shadow>[
                Shadow(
                  offset: Offset(5.0, 5.0),
                  blurRadius: 12.0,
                  color: Colors.black54,
                ),
                Shadow(
                  offset: Offset(-3.0, 3.0),
                  blurRadius: 12.0,
                  color: Colors.black54,
                ),
              ],
            )),
      );
    });
    return Column(children: resultList);
  }

  Widget getResultSummary(ResultBloc resultBloc) {
    return SliverList(
      delegate: SliverChildListDelegate(
        [Divider(color: Colors.transparent), getSummary(resultBloc)],
      ),
    );
  }

  Widget getResults(ResultBloc resultBloc) {
    return SliverGrid(
      delegate: SliverChildListDelegate(
        getResultData(resultBloc),
      ),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 5.0,
        crossAxisSpacing: 5.0,
        childAspectRatio: 1.1,
      ),
    );
  }

  List<Widget> getResultData(ResultBloc resultBloc) {
    List<Widget> data = List();

    resultBloc.resultRepository.getResults().forEach((element) {
      data.add(getResultWidget(element));
    });
    return data;
  }

  Widget getResultWidget(ResultExt element) {
    bool hasHardware = Cache().hasHardware;
    bool blur = (!hasHardware && element.isHardware());
    /* print("Blur: " +
        element.getDescription() +
        ": " +
        blur.toString() +
        " hasHardware:" +
        hasHardware.toString() +
        " isHw: " +
        element.isHardware().toString()); */
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        blur
            ? Stack(children: [
                Image.asset(
                  element.getImage(),
                  height: 80,
                  //color: Colors.white12,
                ),
                Image.asset(
                  element.getImage(),
                  height: 80,
                  color: Colors.black54,
                ),
              ])
            : Image.asset(
                element.getImage(),
                height: 80,
              ),
        SizedBox(
          width: 10,
        ),
        Text(
          element.data.toStringAsFixed(0),
          style: GoogleFonts.archivoBlack(fontSize: 28, color: blur ? Colors.white30 : Colors.white),
        ),
        Text(
          t(element.getDescription()),
          style: GoogleFonts.archivoBlack(fontSize: 14, color: blur ? Colors.white30 : Colors.white),
          textAlign: TextAlign.left,
        ),
      ],
    );
  }
}