import 'dart:collection';

import 'package:aitrainer_app/bloc/test_set_control/test_set_control_bloc.dart';
import 'package:aitrainer_app/bloc/test_set_execute/test_set_execute_bloc.dart';
import 'package:aitrainer_app/bloc/test_set_new/test_set_new_bloc.dart';
import 'package:aitrainer_app/bloc/training_plan/training_plan_bloc.dart';
import 'package:aitrainer_app/library/custom_icon_icons.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/customer_training_plan_details.dart';
import 'package:aitrainer_app/model/exercise_plan_detail.dart';
import 'package:aitrainer_app/model/exercise_type.dart';

import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar.dart';
import 'package:aitrainer_app/widgets/exercise_save.dart';
import 'package:aitrainer_app/widgets/number_picker.dart';
import 'package:flutter/material.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';

// ignore: must_be_immutable
class TrainingPlanExercise extends StatelessWidget with Trans {
  @override
  Widget build(BuildContext context) {
    final HashMap args = ModalRoute.of(context)!.settings.arguments as HashMap;
    final CustomerTrainingPlanDetails detail = args['customerTrainingPlanDetails'];
    // ignore: close_sinks
    final TrainingPlanBloc bloc = BlocProvider.of<TrainingPlanBloc>(context);

    setContext(context);
    return Scaffold(
      appBar: AppBarNav(depth: 1),
      body: Container(
        height: double.infinity,
        width: double.infinity,
        padding: EdgeInsets.all(20),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: Cache().userLoggedIn!.sex == "m"
                ? AssetImage("asset/image/WT_black_background.jpg")
                : AssetImage("asset/image/WT_Results_for_female.jpg"),
            fit: BoxFit.cover,
            alignment: Alignment.center,
          ),
        ),
        child: BlocConsumer<TrainingPlanBloc, TrainingPlanState>(listener: (context, state) {
          if (state is TrainingPlanError) {
            ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white))));
          }
        }, builder: (context, state) {
          return ModalProgressHUD(
            child: getExercises(bloc, detail),
            inAsyncCall: state is TrainingPlanLoading,
            opacity: 0.5,
            color: Colors.black54,
            progressIndicator: CircularProgressIndicator(),
          );
        }),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () => {
          Navigator.of(context).pop(),
          bloc.add(TrainingPlanSaveExercise(detail: detail)),
        },
        backgroundColor: Colors.orange[800],
        icon: Icon(CustomIcon.save),
        label: Text(
          t("Save"),
          style: GoogleFonts.inter(fontWeight: FontWeight.bold, fontSize: 16),
        ),
      ),
    );
  }

  Widget getExercises(TrainingPlanBloc bloc, CustomerTrainingPlanDetails detail) {
    final String noTestTextWithWeight = "Please try to execute this exercise with exact weight and repeats what is suggested";
    final String noTestTextNoWeight = "Please try to execute this exercise with exact repeats what is suggested";
    return ExerciseSave(
      exerciseName: detail.exerciseType!.nameTranslation,
      exerciseDescription: detail.exerciseType!.descriptionTranslation,
      exerciseTask: detail.exerciseType!.unitQuantityUnit != null
          ? detail.weight == -1
              ? t("Please take a relative bigger weight and repeat 12-20 times and do your best! MAXIMIZE it!")
              : noTestTextWithWeight
          : detail.repeats == -1
              ? t("Please repeat as much times as you can! MAXIMIZE it!")
              : noTestTextNoWeight,
      unit: detail.exerciseType!.unit,
      unitQuantityUnit: detail.exerciseType!.unitQuantityUnit,
      hasUnitQuantity: detail.exerciseType!.unitQuantityUnit != null,
      weight: detail.weight == -1 ? 30 : detail.weight,
      repeats: detail.repeats == -1 ? 12 : detail.repeats,
      set: detail.set,
      exerciseNr: detail.exercises.length + 1,
      onUnitQuantityChanged: (value) => bloc.add(TrainingPlanWeightChange(weight: value, detail: detail)),
      onQuantityChanged: (value) => bloc.add(TrainingPlanRepeatsChange(repeats: value.toInt(), detail: detail)),
      exerciseTypeId: detail.exerciseType!.exerciseTypeId,
    );
  }

  Widget getExerciseForm(TrainingPlanBloc bloc, CustomerTrainingPlanDetails detail) {
    return Container(
        padding: const EdgeInsets.only(top: 10, left: 25, right: 25),
        child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Column(
              children: [
                Text(
                  detail.exerciseType!.nameTranslation,
                  style: GoogleFonts.archivoBlack(
                    fontWeight: FontWeight.bold,
                    fontSize: 24,
                    color: Colors.white,
                    shadows: <Shadow>[
                      Shadow(
                        offset: Offset(2.0, 2.0),
                        blurRadius: 6.0,
                        color: Colors.black54,
                      ),
                      Shadow(
                        offset: Offset(-3.0, 3.0),
                        blurRadius: 12.0,
                        color: Colors.black54,
                      ),
                    ],
                  ),
                  overflow: TextOverflow.fade,
                  textAlign: TextAlign.center,
                  maxLines: 2,
                  softWrap: true,
                ),
                Divider(
                  color: Colors.transparent,
                ),
                Divider(),
                detail.weight != -1 ? numberPickForm(bloc, detail) : numberPickForm(bloc, detail),
              ],
            )));
  }

  Widget numberPickForm(TrainingPlanBloc bloc, CustomerTrainingPlanDetails detail) {
    final String strTimes = detail.repeats!.toStringAsFixed(1); // : "maximum";

    List<Widget> listWidgets = [
      GestureDetector(
          onTap: () => {},
          child: RichText(
            text: TextSpan(
                style: GoogleFonts.inter(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.yellow[300],
                ),
                children: [
                  TextSpan(text: t("Please repeat with ")),
                  TextSpan(
                    text: detail.weight!.toStringAsFixed(1) + " " + detail.exerciseType!.unitQuantityUnit!,
                    style: GoogleFonts.inter(
                      decoration: TextDecoration.underline,
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.yellow[100],
                    ),
                  ),
                  TextSpan(text: t("hu_with") + " "),
                  TextSpan(
                      text: strTimes + " ",
                      style: GoogleFonts.inter(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: Colors.yellow[100],
                      )),
                  TextSpan(
                      text: t(
                    "times!",
                  )),
                ]),
          )),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          NumberPickerWidget(
              minValue: 0,
              maxValue: 200,
              initalValue: detail.repeats!,
              unit: t("reps"),
              color: Colors.yellow[50]!,
              onChange: (value) => {}),
          TextButton(
              style: TextButton.styleFrom(
                padding: EdgeInsets.all(0),
                primary: Colors.white,
                onSurface: Colors.blueAccent,
              ),
              onPressed: () => {},
              child: Stack(
                alignment: Alignment.center,
                children: [
                  Image.asset('asset/icon/gomb_orange_c.png', width: 140, height: 60),
                  Text(
                    t("Save"),
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),
                ],
              )),
        ],
      ),
    ];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: listWidgets,
    );
  }
}
