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/model/cache.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/bottom_bar_multiple_exercises.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 TestSetControl extends StatelessWidget with Trans {
  @override
  Widget build(BuildContext context) {
    final HashMap args = ModalRoute.of(context)!.settings.arguments as HashMap;
    final ExerciseType exerciseType = args['exerciseType'];
    final ExercisePlanDetail exercisePlanDetail = args['exercisePlanDetail'];
    // ignore: close_sinks
    TestSetExecuteBloc executeBloc = args['testSetExecuteBloc'];

    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_Results_for_men.jpg")
                  : AssetImage("asset/image/WT_Results_for_female.jpg"),
              fit: BoxFit.cover,
              alignment: Alignment.center,
            ),
          ),
          child: BlocProvider(
            create: (context) =>
                TestSetControlBloc(exercisePlanDetail: exercisePlanDetail, executeBloc: executeBloc, exerciseType: exerciseType),
            child: BlocConsumer<TestSetControlBloc, TestSetControlState>(listener: (context, state) {
              if (state is TestSetControlError) {
                ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white))));
              }
            }, builder: (context, state) {
              final bloc = BlocProvider.of<TestSetControlBloc>(context);
              return ModalProgressHUD(
                child: getExercisForm(bloc, exercisePlanDetail),
                inAsyncCall: state is TestSetNewLoading,
                opacity: 0.5,
                color: Colors.black54,
                progressIndicator: CircularProgressIndicator(),
              );
            }),
          )),
      bottomNavigationBar: BottomBarMultipleExercises(
        isSet: executeBloc.miniTestSet == true,
        exerciseTypeId: exerciseType.exerciseTypeId,
      ),
    );
  }

  Widget getExercisForm(TestSetControlBloc bloc, ExercisePlanDetail exercisePlanDetail) {
    return Container(
        padding: const EdgeInsets.only(top: 10, left: 25, right: 25),
        child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Column(
              children: [
                Text(
                  exercisePlanDetail.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(),
                numberPickForm(bloc),
              ],
            )));
  }

  Widget numberPickForm(TestSetControlBloc bloc) {
    final String strTimes = bloc.step == 2 ? bloc.initQuantity.toStringAsFixed(0) : "maximum";

    String title = (bloc.step + 1).toString() + "/4 " + t("Control Exercise:");

    List<Widget> listWidgets = [
      Text(
        title,
        style: GoogleFonts.inter(color: Colors.yellow[300], fontSize: 18, fontWeight: FontWeight.bold),
      ),
      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: bloc.initUnitQuantity.toStringAsFixed(0) + " " + bloc.exercisePlanDetail.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: bloc.initQuantity.round(),
              unit: t("reps"),
              color: Colors.yellow[50]!,
              onChange: (value) => {bloc.add(TestSetControlQuantityChange(quantity: value.toDouble()))}),
          TextButton(
              style: TextButton.styleFrom(
                padding: EdgeInsets.all(0),
                primary: Colors.white,
                onSurface: Colors.blueAccent,
              ),
              onPressed: () => {
                    bloc.add(TestSetControlSubmit()),
                    {
                      Navigator.of(context).pop(),
                    }
                  },
              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,
    );
  }
}
