import 'dart:collection';

import 'package:aitrainer_app/bloc/exercise_plan/exercise_plan_bloc.dart';
import 'package:aitrainer_app/bloc/exercise_plan_custom_add/exercise_plan_custom_add_bloc.dart';
import 'package:aitrainer_app/util/app_language.dart';
import 'package:aitrainer_app/model/workout_menu_tree.dart';
import 'package:aitrainer_app/repository/exercise_plan_repository.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar.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:keyboard_actions/keyboard_actions.dart';
import 'package:keyboard_actions/keyboard_actions_config.dart';
import 'package:keyboard_actions/keyboard_actions_item.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

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

class _ExercisePlanDetailAddPage extends State<ExercisePlanDetailAddPage> 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) {
    LinkedHashMap args = ModalRoute.of(context)!.settings.arguments as LinkedHashMap;
    // ignore: close_sinks
    final ExercisePlanBloc planBloc = args['bloc'];
    final WorkoutMenuTree workoutMenuTree = args['workoutTreeItem'];
    final ExercisePlanRepository exercisePlanRepository = planBloc.exercisePlanRepository;
    setContext(context);

    return BlocProvider(
        create: (context) =>
            ExercisePlanCustomAddBloc(exercisePlanRepository: exercisePlanRepository, planBloc: planBloc, workoutMenuTree: workoutMenuTree)
              ..add(ExercisePlanCustomAddLoad()),
        child: BlocConsumer<ExercisePlanCustomAddBloc, ExercisePlanCustomAddState>(
          listener: (context, state) {
            if (state is ExercisePlanCustomAddError) {
              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<ExercisePlanCustomAddBloc>(context);
            return ModalProgressHUD(
              child: getForm(bloc, workoutMenuTree),
              inAsyncCall: state is ExercisePlanCustomAddLoading,
              opacity: 0.5,
              color: Colors.black54,
              progressIndicator: CircularProgressIndicator(),
            );
          },
        ));
  }

  Widget getForm(ExercisePlanCustomAddBloc bloc, WorkoutMenuTree workoutMenuTree) {
    String exerciseName = "";
    if (bloc.exercisePlanRepository.getActualPlanDetail() == null || bloc.serie == null) {
      return Offstage();
    }

    exerciseName = AppLanguage().appLocal == Locale("en")
        ? bloc.exercisePlanRepository.getActualPlanDetail()!.exerciseType!.name
        : bloc.exercisePlanRepository.getActualPlanDetail()!.exerciseType!.nameTranslation;

    final bool weightVisible = bloc.exercisePlanRepository.getActualPlanDetail()!.exerciseType!.unitQuantityUnit != null;
    String summary = bloc.serie!.toStringAsFixed(0) + " x " + bloc.quantity.toStringAsFixed(0);
    if (bloc.quantityUnit > 0) {
      summary += " x " + bloc.quantityUnit.toStringAsFixed(1) + " kg";
    }
    final String unit = bloc.exercisePlanRepository.getActualPlanDetail()!.exerciseType!.unit;
    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: KeyboardActions(
              config: _buildConfig(context),
              child: Container(
                  child: SingleChildScrollView(
                padding: const 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 Exercise 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.serie!.toStringAsFixed(0),
                      focusNode: _nodeText1,
                      keyboardType: TextInputType.number,
                      style: GoogleFonts.archivoBlack(fontSize: 60, color: Colors.yellow[200]),
                      onChanged: (value) => {bloc.add(ExercisePlanCustomAddChangeSerie(quantity: double.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.quantity.toStringAsFixed(0),
                      keyboardType: TextInputType.number,
                      style: GoogleFonts.archivoBlack(fontSize: 60, color: Colors.yellow[200]),
                      onChanged: (value) => {bloc.add(ExercisePlanCustomAddChangeQuantity(quantity: double.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.quantityUnit.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(ExercisePlanCustomAddChangeQuantityUnit(quantity: 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(ExercisePlanCustomAddRemove()),
                          Navigator.of(context).pop(),
                        },
                        child: Stack(
                          alignment: Alignment.center,
                          children: [
                            Image.asset('asset/icon/gomb_pink_b.png', width: 140, height: 60),
                            Text(
                              t("Delete"),
                              style: TextStyle(fontSize: 16, color: Colors.white),
                            ),
                          ],
                        ),
                      ),
                      TextButton(
                          onPressed: () => {
                                bloc.add(ExercisePlanCustomAddSubmit()),
                                Navigator.of(context).pop(),
                              },
                          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),
                              ),
                            ],
                          )),
                    ],
                  ),
                ]),
              )))),
    ));
  }
}
