import 'dart:collection';

import 'package:aitrainer_app/bloc/custom_exercise_form_bloc.dart';
import 'package:aitrainer_app/localization/app_localization.dart';
import 'package:aitrainer_app/model/exercise_type.dart';
import 'package:aitrainer_app/repository/exercise_repository.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_bloc/flutter_form_bloc.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';

class CustomExercisePage extends StatefulWidget {
  _CustomExerciseNewPageState createState() => _CustomExerciseNewPageState();
}

class _CustomExerciseNewPageState extends State<CustomExercisePage> with Logging {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    final ExerciseType exerciseType = ModalRoute.of(context).settings.arguments;

    return BlocProvider(
        create: (context) => CustomExerciseFormBloc(exerciseRepository: ExerciseRepository()),
        child: Builder(builder: (context) {
          final exerciseBloc = BlocProvider.of<CustomExerciseFormBloc>(context);
          exerciseBloc.exerciseRepository.setExerciseType(exerciseType);

          return Scaffold(
              key: _scaffoldKey,
              resizeToAvoidBottomInset: true,
              appBar: AppBar(
                backgroundColor: Colors.transparent,
                title: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Image.asset(
                      'asset/image/WT_long_logo.png',
                      fit: BoxFit.cover,
                      height: 65.0,
                    ),
                  ],
                ),
                leading: IconButton(
                  icon: Icon(Icons.arrow_back, color: Colors.white),
                  onPressed: () => Navigator.of(context).pop(),
                ),
              ),
              body: FormBlocListener<CustomExerciseFormBloc, String, String>(
                /* onSubmitting: (context, state) {
                    LoadingDialog.show(context);
                  }, */
                onSuccess: (context, state) {},
                onFailure: (context, state) {
                  Scaffold.of(context).showSnackBar(SnackBar(
                      backgroundColor: Colors.orange, content: Text(state.failureResponse, style: TextStyle(color: Colors.white))));
                },
                child: ModalProgressHUD(
                  child: Container(
                      width: MediaQuery.of(context).size.width,
                      height: MediaQuery.of(context).size.height,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('asset/image/WT_light_background.png'),
                          fit: BoxFit.fill,
                          alignment: Alignment.center,
                        ),
                      ),
                      child: CustomScrollView(scrollDirection: Axis.vertical, slivers: [
                        SliverList(
                          delegate: SliverChildListDelegate([
                            Container(
                                padding: EdgeInsets.only(top: 20, left: 25, right: 25),
                                alignment: Alignment.center,
                                child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
                                  Text("Custom Exercise",
                                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Colors.deepOrange)),
                                  columnQuantityUnit(exerciseBloc),
                                  columnQuantity(exerciseBloc),
                                ])),
                          ]),
                        ),
                        gridCalculation(exerciseBloc)
                      ])),
                  inAsyncCall: exerciseBloc.loading == true,
                  opacity: 0.5,
                  color: Colors.black54,
                  progressIndicator: CircularProgressIndicator(),
                ),
              ));
        }));
  }

  Column columnQuantityUnit(CustomExerciseFormBloc bloc) {
    Column column = Column();
    if (bloc.exerciseRepository.exerciseType != null && bloc.exerciseRepository.exerciseType.unitQuantity == "1") {
      column = Column(children: [
        TextFieldBlocBuilder(
          textFieldBloc: bloc.unitQuantityField,
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 16, color: Colors.lightBlue, fontWeight: FontWeight.bold),
          inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r"[\d.]"))],
          onChanged: (input) => {log("UnitQuantity value $input"), bloc.exerciseRepository.setUnitQuantity(double.parse(input))},
          decoration: InputDecoration(
            fillColor: Colors.white,
            filled: false,
            hintStyle: TextStyle(fontSize: 12, color: Colors.black54, fontWeight: FontWeight.w100),
            hintText: AppLocalizations.of(context).translate("The number of the exercise done with"),
            labelStyle: TextStyle(fontSize: 12, color: Colors.lightBlue),
            labelText: AppLocalizations.of(context).translate(bloc.exerciseRepository.exerciseType.unitQuantityUnit),
          ),
        ),
        new InkWell(
          child: new Text(AppLocalizations.of(context).translate(bloc.exerciseRepository.exerciseType.unitQuantityUnit),
              style: TextStyle(fontSize: 12)),
        ),
      ]);
    }
    return column;
  }

  Column columnQuantity(CustomExerciseFormBloc bloc) {
    Column column = Column(children: [
      TextFieldBlocBuilder(
        textFieldBloc: bloc.quantityField,
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 20, color: Colors.deepOrange, fontWeight: FontWeight.bold),
        inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r"[\d.]"))],
        onChanged: (input) => {
          log("Quantity value $input"),
          bloc.exerciseRepository.setQuantity(double.parse(input)),
          bloc.exerciseRepository.setUnit(bloc.exerciseRepository.exerciseType.unit)
        },
        decoration: InputDecoration(
          fillColor: Colors.white,
          filled: false,
          hintStyle: TextStyle(fontSize: 12, color: Colors.black54, fontWeight: FontWeight.w100),
          hintText: AppLocalizations.of(context).translate("The number of the exercise"),
          labelStyle: TextStyle(fontSize: 12, color: Colors.deepOrange),
          labelText: AppLocalizations.of(context).translate(bloc.exerciseRepository.exerciseType.unit),
        ),
      ),
    ]);

    return column;
  }

  SliverGrid gridCalculation(CustomExerciseFormBloc bloc) {
    LinkedHashMap args = LinkedHashMap();
    return SliverGrid(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 10.0,
          crossAxisSpacing: 10.0,
          childAspectRatio: 2.0,
        ),
        delegate: SliverChildListDelegate(
          [
            TextFieldBlocBuilder(
                readOnly: true,
                textFieldBloc: bloc.rmWendlerField,
                padding: EdgeInsets.only(left: 10),
                style: TextStyle(color: Colors.deepOrange, fontSize: 12),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM by Wendler: ",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rmWathenField,
                style: TextStyle(color: Colors.deepOrange, fontSize: 12),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM by Wahten: ",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rmOconnerField,
                style: TextStyle(color: Colors.deepOrange, fontSize: 12),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM by O'Conner: ",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rmMayhewField,
                style: TextStyle(color: Colors.deepOrange, fontSize: 12),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM by Mayhew: ",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rmAverageField,
                style: TextStyle(color: Colors.blueAccent, fontSize: 12),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM Average: ",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rm90Field,
                style: TextStyle(color: Colors.deepOrange, fontSize: 12),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM 90%: ",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rm75Field,
                style: TextStyle(color: Colors.deepOrange, fontSize: 12, fontWeight: FontWeight.normal),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM 75%: ",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rm75OconnorField,
                style: TextStyle(color: Colors.deepOrange, fontSize: 12, fontWeight: FontWeight.normal),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM 75%: by O'Connor",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rm75WendlerField,
                style: TextStyle(color: Colors.deepOrange, fontSize: 12, fontWeight: FontWeight.normal),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM 75% by Wendler: ",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rm80Field,
                style: TextStyle(color: Colors.deepOrange, fontSize: 12),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM 80%: ",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rm70Field,
                style: TextStyle(color: Colors.deepOrange, fontSize: 12),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM 70%: ",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rm60Field,
                style: TextStyle(color: Colors.deepOrange, fontSize: 12),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM 60%: ",
                )),
            TextFieldBlocBuilder(
                readOnly: true,
                padding: EdgeInsets.only(left: 10),
                maxLines: 1,
                textFieldBloc: bloc.rm50Field,
                style: TextStyle(color: Colors.deepOrange, fontSize: 12),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  filled: false,
                  labelText: "1RM 50%: ",
                )),
            RaisedButton(
                padding: EdgeInsets.all(0),
                textColor: Colors.white,
                color: Colors.blue,
                focusColor: Colors.blueAccent,
                onPressed: () => {
                      args['exerciseRepository'] = bloc.exerciseRepository,
                      args['percent'] = 0.75,
                      args['readonly'] = true,
                      Navigator.of(context).pushNamed('exerciseControlPage', arguments: args)
                    },
                child: Text(
                  "Control with 75%",
                  style: TextStyle(fontSize: 12),
                )),
            RaisedButton(
                padding: EdgeInsets.all(0),
                textColor: Colors.white,
                color: Colors.green,
                focusColor: Colors.blueAccent,
                onPressed: () => {
                      args['exerciseRepository'] = bloc.exerciseRepository,
                      args['percent'] = 0.5,
                      args['readonly'] = true,
                      Navigator.of(context).pushNamed('exerciseControlPage', arguments: args)
                    },
                child: Text(
                  "Control with 50%",
                  style: TextStyle(fontSize: 12),
                )),
          ],
        ));
  }

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