import 'dart:collection';

import 'package:aitrainer_app/bloc/exercise_execute_plan/exercise_execute_plan_bloc.dart';
import 'package:aitrainer_app/bloc/exercise_execute_plan_add/exercise_execute_plan_add_bloc.dart';
import 'package:aitrainer_app/library/custom_icon_icons.dart';
import 'package:aitrainer_app/util/app_language.dart';
import 'package:aitrainer_app/model/workout_menu_tree.dart';
import 'package:aitrainer_app/repository/exercise_repository.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar.dart';
import 'package:aitrainer_app/widgets/number_picker.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

class ExerciseExecutePlanAddPage extends StatefulWidget {
  _ExerciseExecuteAddPage createState() => _ExerciseExecuteAddPage();
}

class _ExerciseExecuteAddPage extends State<ExerciseExecutePlanAddPage> with Trans {
  final ScrollController _controller = ScrollController();
  double offset = 0;

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    LinkedHashMap arguments = ModalRoute.of(context)!.settings.arguments as LinkedHashMap;
    // ignore: close_sinks
    final ExerciseExecutePlanBloc planBloc = arguments['blocExerciseByPlan'];
    final int customerId = arguments['customerId'];
    final WorkoutMenuTree workoutTree = arguments['workoutTree'];
    final ExerciseRepository exerciseRepository = ExerciseRepository();
    setContext(context);

    return BlocProvider(
        create: (context) => ExerciseExecutePlanAddBloc(
            exerciseRepository: exerciseRepository,
            exercisePlanRepository: planBloc.exercisePlanRepository,
            customerId: customerId,
            workoutTree: workoutTree,
            planBloc: planBloc)
          ..add(ExerciseExecutePlanAddLoad()),
        child: BlocConsumer<ExerciseExecutePlanAddBloc, ExerciseExecutePlanAddState>(listener: (context, state) {
          if (state is ExerciseExecutePlanAddError) {
            ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white))));
          }
        }, builder: (context, state) {
          // ignore: close_sinks
          final exerciseBloc = BlocProvider.of<ExerciseExecutePlanAddBloc>(context);
          if (state is ExerciseExecutePlanAddReady && _controller.hasClients) {
            _controller.animateTo(exerciseBloc.scrollOffset, duration: Duration(milliseconds: 300), curve: Curves.easeIn);
          }
          return ModalProgressHUD(
            child: getControlForm(exerciseBloc),
            inAsyncCall: state is ExerciseExecutePlanAddLoading,
            opacity: 0.5,
            color: Colors.black54,
            progressIndicator: CircularProgressIndicator(),
          );
        }));
  }

  Widget getControlForm(ExerciseExecutePlanAddBloc exerciseBloc) {
    if (exerciseBloc.exerciseRepository.exerciseType == null || exerciseBloc.quantity == null) {
      return Offstage();
    }
    String exerciseName = AppLanguage().appLocal == Locale("en")
        ? exerciseBloc.exerciseRepository.exerciseType!.name
        : exerciseBloc.exerciseRepository.exerciseType!.nameTranslation;

    return Form(
      child: Scaffold(
        resizeToAvoidBottomInset: true,
        appBar: AppBarNav(depth: 1),
        body: Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('asset/image/WT_black_background.jpg'),
                fit: BoxFit.fill,
                alignment: Alignment.center,
              ),
            ),
            child: Container(
                padding: const EdgeInsets.only(top: 25, left: 25, right: 25),
                child: SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  physics: BouncingScrollPhysics(),
                  controller: _controller,
                  child: Column(mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[
                    Text(
                      t("Save Exercise"),
                      style: GoogleFonts.inter(fontSize: 16, color: Colors.orange[50]),
                    ),
                    Text(
                      exerciseName,
                      style: GoogleFonts.archivoBlack(
                        fontSize: 24,
                        color: Colors.orange[700],
                        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,
                          ),
                        ],
                      ),
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.fade,
                      maxLines: 3,
                      softWrap: true,
                    ),
                    Divider(
                      color: Colors.transparent,
                    ),
                    Divider(),
                    Column(
                      children: repeatExercises(exerciseBloc),
                    ),
                    Divider(),
                  ]),
                ))),
      ),
    );
  }

  List<Column> repeatExercises(ExerciseExecutePlanAddBloc exerciseBloc) {
    List<Column> listColumns = [];
    for (int i = 0; i < exerciseBloc.countSteps; i++) {
      Column col = Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Divider(
            color: Colors.transparent,
          ),
          RichText(
            text: TextSpan(
                style: GoogleFonts.inter(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.yellow[300],
                  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,
                    ),
                  ],
                ),
                children: [
                  TextSpan(text: t("Execute the") + " "),
                  TextSpan(
                    text: (i + 1).toString() + ". ",
                    style: GoogleFonts.inter(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.yellow[600],
                    ),
                  ),
                  TextSpan(text: t("set!"))
                ]),
          ),
          Divider(
            color: Colors.transparent,
          ),
          Row(mainAxisAlignment: MainAxisAlignment.start, children: [
            exerciseBloc.exerciseRepository.exerciseType!.unitQuantityUnit == null
                ? Offstage()
                : NumberPickerWidget(
                    minValue: 0,
                    maxValue: 1000,
                    fontSize: 16,
                    initalValue: exerciseBloc.unitQuantity!.toInt(),
                    unit: t(exerciseBloc.exerciseRepository.exerciseType!.unitQuantityUnit!),
                    color: Colors.yellow[50]!,
                    onChange: (value) => {exerciseBloc.add(ExerciseExecutePlanAddChangeUnitQuantity(quantity: value.toDouble()))}),
            NumberPickerWidget(
                minValue: 0,
                maxValue: 200,
                fontSize: 16,
                initalValue: exerciseBloc.quantity!.toInt(),
                unit: t(exerciseBloc.exerciseRepository.exerciseType!.unit), //t("repeat"),
                color: Colors.yellow[50]!,
                onChange: (value) => {exerciseBloc.add(ExerciseExecutePlanAddChangeQuantity(quantity: value.toDouble()))}),
          ]),
          TextButton(
              style: TextButton.styleFrom(
                padding: EdgeInsets.all(0),
                primary: Colors.white,
                onSurface: Colors.blueAccent,
              ),
              onPressed: () => {
                    if (exerciseBloc.step == i + 1) {exerciseBloc.add(ExerciseExecutePlanAddSubmit())},
                    if (i + 1 == exerciseBloc.countSteps) {Navigator.of(context).pop()}
                  },
              child: exerciseBloc.step == i + 1
                  ? 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),
                        ),
                      ],
                    )
                  : Stack(
                      alignment: Alignment.center,
                      children: getButton(i + 1, exerciseBloc),
                    )),
          /*  Row(children: [
            NumberPicker.horizontal(
              highlightSelectedValue: (i + 1) == exerciseBloc.step,
              initialValue: exerciseBloc.quantity.toInt(),
              minValue: 0,
              maxValue: 200,
              step: 1,
              textStyle: TextStyle(fontWeight: FontWeight.bold),
              textStyleHighlighted: TextStyle(fontSize: 24, color: Colors.deepOrange, fontWeight: FontWeight.bold),
              onChanged: (value) => {exerciseBloc.add(ExerciseExecutePlanAddChangeQuantity(quantity: value.toDouble()))},
              listViewHeight: 80,
              //decoration: _decoration,
            ),
            Text(t("repeat")),
          ]), */
          /* RaisedButton(
              padding: EdgeInsets.all(0),
              textColor: Colors.white,
              color: exerciseBloc.step == i + 1 ? Colors.blue : Colors.black26,
              focusColor: Colors.blueAccent,
              onPressed: () => {
                    if (exerciseBloc.step == i + 1) {exerciseBloc.add(ExerciseExecutePlanAddSubmit())},
                    if (i + 1 == exerciseBloc.countSteps) {Navigator.of(context).pop()}
                  },
              child: Text(
                t("Save"),
                style: TextStyle(fontSize: 12),
              )), */
          Divider(),
        ],
      );
      listColumns.add(col);
    }
    return listColumns;
  }

  List<Widget> getButton(int step, ExerciseExecutePlanAddBloc exerciseBloc) {
    List<Widget> widgets = [];
    if (step < exerciseBloc.step) {
      widgets.add(Icon(
        CustomIcon.check_circle,
        color: Color(0xffb4f500),
        size: 36,
      ));
    } else {
      widgets.add(Icon(
        CustomIcon.question,
        color: Colors.grey[700],
        size: 36,
      ));
    }
    return widgets;
  }
}
