import 'package:aitrainer_app/bloc/training_plan/training_plan_bloc.dart';
import 'package:aitrainer_app/util/app_language.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar_min.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

class TrainingPlanCustomAddPage extends StatefulWidget {
  @override
  _ExercisePlanDetailAddPage createState() => _ExercisePlanDetailAddPage();
}

class _ExercisePlanDetailAddPage extends State<TrainingPlanCustomAddPage> with Trans {
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  final FocusNode _nodeText3 = FocusNode();

  KeyboardActionsConfig _buildConfig(BuildContext context) {
    return KeyboardActionsConfig(
      keyboardActionsPlatform: KeyboardActionsPlatform.ALL,
      keyboardBarColor: Colors.grey[200],
      nextFocus: true,
      actions: [
        KeyboardActionsItem(focusNode: _nodeText2, toolbarButtons: [
          (node) {
            return GestureDetector(
              onTap: () => node.unfocus(),
              child: Container(
                padding: EdgeInsets.all(8.0),
                color: Colors.orange[500],
                child: Text(
                  t("Done"),
                  style: TextStyle(color: Colors.white),
                ),
              ),
            );
          }
        ]),
        KeyboardActionsItem(
          focusNode: _nodeText1,
          toolbarButtons: [
            //button 2
            (node) {
              return GestureDetector(
                onTap: () => node.unfocus(),
                child: Container(
                  color: Colors.orange,
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    t("Done"),
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              );
            }
          ],
        ),
        KeyboardActionsItem(
          focusNode: _nodeText3,
          toolbarButtons: [
            //button 2
            (node) {
              return GestureDetector(
                onTap: () => node.unfocus(),
                child: Container(
                  color: Colors.orange,
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    t("Done"),
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              );
            }
          ],
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    setContext(context);

    return 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) {
        // ignore: close_sinks
        final bloc = BlocProvider.of<TrainingPlanBloc>(context);
        return ModalProgressHUD(
          child: getForm(bloc),
          inAsyncCall: state is TrainingPlanLoading,
          opacity: 0.5,
          color: Colors.black54,
          progressIndicator: CircularProgressIndicator(),
        );
      },
    );
  }

  Widget getForm(TrainingPlanBloc bloc) {
    if (bloc.getMyDetail() == null) {
      return Offstage();
    }
    String exerciseName = "";

    exerciseName = bloc.getExerciseName(AppLanguage().appLocal);

    final bool weightVisible = bloc.getMyDetail()!.exerciseType!.unitQuantityUnit != null;
    String summary = bloc.getCustomAddSummary();
    if (weightVisible && bloc.getMyDetail()!.weight != null && bloc.getMyDetail()!.weight! > 0) {
      summary += " x " + bloc.getMyDetail()!.weight!.toStringAsFixed(1) + " kg";
    }
    final String unit = bloc.getMyDetail()!.exerciseType!.unit;
    return Form(
        child: Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: AppBarMin(
        back: true,
        onTap: () => Navigator.of(context).popAndPushNamed("myTrainingPlanCustom"),
      ),
      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: KeyboardActions(
              config: _buildConfig(context),
              child: Container(
                  child: SingleChildScrollView(
                padding: EdgeInsets.only(top: 25, left: 95, right: 95),
                scrollDirection: Axis.vertical,
                child: Column(mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[
                  Text(t('Save The Exercise To The Training Plan'),
                      textAlign: TextAlign.center,
                      style: GoogleFonts.inter(
                        fontSize: 14,
                        color: Colors.white,
                      )),
                  Text(
                    exerciseName,
                    textAlign: TextAlign.center,
                    style: GoogleFonts.archivoBlack(fontSize: 18, color: Colors.yellow[200]),
                    overflow: TextOverflow.fade,
                    maxLines: 3,
                    softWrap: true,
                  ),
                  Divider(
                    color: Colors.transparent,
                    height: 30,
                  ),
                  TextFormField(
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.only(left: 25, top: 5, bottom: 5),
                        labelText: t('Serie'),
                        labelStyle: GoogleFonts.inter(fontSize: 20, color: Colors.yellow[50], decorationColor: Colors.black12),
                        fillColor: Colors.white24,
                        filled: true,
                        border: OutlineInputBorder(
                          gapPadding: 8.0,
                          borderRadius: BorderRadius.circular(12.0),
                          borderSide: BorderSide(color: Colors.black26, width: 0.4),
                        ),
                      ),
                      initialValue: bloc.getMyDetail()!.set!.toStringAsFixed(0),
                      focusNode: _nodeText1,
                      keyboardType: TextInputType.number,
                      style: GoogleFonts.archivoBlack(fontSize: 60, color: Colors.yellow[200]),
                      onChanged: (value) => {bloc.add(TrainingPlanSetChange(detail: bloc.getMyDetail()!, set: int.parse(value)))}),
                  Divider(),
                  TextFormField(
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.only(left: 25, top: 5, bottom: 5),
                      labelText: t(unit),
                      fillColor: Colors.white24,
                      labelStyle: GoogleFonts.inter(fontSize: 20, color: Colors.yellow[50]),
                      filled: true,
                      border: OutlineInputBorder(
                        gapPadding: 4.0,
                        borderRadius: BorderRadius.circular(12.0),
                        borderSide: BorderSide(color: Colors.green[50]!, width: 0.4),
                      ),
                    ),
                    focusNode: _nodeText2,
                    initialValue: bloc.getMyDetail()!.repeats!.toStringAsFixed(0),
                    keyboardType: TextInputType.number,
                    style: GoogleFonts.archivoBlack(fontSize: 60, color: Colors.yellow[200]),
                    onChanged: (value) => bloc.add(TrainingPlanRepeatsChange(detail: bloc.getMyDetail()!, repeats: int.parse(value))),
                  ),
                  Divider(),
                  weightVisible
                      ? TextFormField(
                          decoration: InputDecoration(
                            contentPadding: EdgeInsets.only(left: 25, top: 5, bottom: 5),
                            labelText: t('Weight'),
                            fillColor: Colors.white24,
                            labelStyle: GoogleFonts.inter(fontSize: 20, color: Colors.yellow[50]),
                            filled: true,
                            border: OutlineInputBorder(
                              gapPadding: 2.0,
                              borderRadius: BorderRadius.circular(12.0),
                              borderSide: BorderSide(color: Colors.green[50]!, width: 0.4),
                            ),
                          ),
                          focusNode: _nodeText3,
                          initialValue: bloc.getMyDetail()!.weight!.toStringAsFixed(1),
                          keyboardType: TextInputType.numberWithOptions(decimal: true),
                          style: GoogleFonts.archivoBlack(fontSize: 60, color: Colors.yellow[200]),
                          onChanged: (value) => {
                                if (value.isNotEmpty)
                                  {
                                    value = value.replaceFirst(",", "."),
                                    value = value.replaceAll(RegExp(r'[^0-9.]'), ""),
                                    bloc.add(TrainingPlanWeightChange(detail: bloc.getMyDetail()!, weight: double.parse(value))),
                                  }
                              })
                      : Offstage(),
                  Divider(),
                  Text(
                    summary,
                    style: TextStyle(fontSize: 24, fontWeight: FontWeight.normal, color: Colors.yellow[50]),
                  ),
                  Divider(),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      TextButton(
                          onPressed: () => {
                                bloc.add(TrainingPlanAddExerciseType()),
                                Navigator.of(context).popAndPushNamed("myTrainingPlanCustom"),
                              },
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              Image.asset('asset/icon/gomb_zold_b-1.png', width: 140, height: 60),
                              Text(
                                t("Save"),
                                style: TextStyle(fontSize: 16, color: Colors.white),
                              ),
                            ],
                          )),
                    ],
                  ),
                ]),
              )))),
    ));
  }
}