import 'dart:collection';

import 'package:aitrainer_app/bloc/training_plan/training_plan_bloc.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:aitrainer_app/util/enums.dart';
import 'package:aitrainer_app/util/track.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar.dart';
import 'package:aitrainer_app/widgets/bottom_nav.dart';
import 'package:aitrainer_app/widgets/dialog_common.dart';
import 'package:aitrainer_app/widgets/image_button.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 MyTrainingPlans extends StatelessWidget with Trans, Logging {
  @override
  Widget build(BuildContext context) {
    setContext(context);

    return Scaffold(
        appBar: AppBarNav(depth: 0),
        body: Container(
          padding: EdgeInsets.all(10),
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('asset/image/WT_menu_dark.jpg'),
              fit: BoxFit.cover,
              alignment: Alignment.center,
            ),
          ),
          child: BlocConsumer<TrainingPlanBloc, TrainingPlanState>(
            listener: (context, state) {
              if (state is TrainingPlanError) {
                showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return DialogCommon(
                        warning: true,
                        title: t("Warning"),
                        descriptions: t(state.message),
                        text: "OK",
                        onTap: () => Navigator.of(context).pop(),
                        onCancel: () => {
                          Navigator.of(context).pop(),
                        },
                      );
                    });
              } else if (state is TrainingPlanFinished) {
                Navigator.of(context).pop();
                final TrainingPlanBloc bloc = BlocProvider.of<TrainingPlanBloc>(context);
                bloc.setMyPlan(Cache().myTrainingPlan);
                Navigator.of(context).pushNamed("myTrainingPlanExecute", arguments: bloc);
              }
            },
            builder: (context, state) {
              final TrainingPlanBloc bloc = BlocProvider.of<TrainingPlanBloc>(context);
              return ModalProgressHUD(
                child: getPrograms(bloc),
                inAsyncCall: state is TrainingPlanLoading,
                opacity: 0.5,
                color: Colors.black54,
                progressIndicator: CircularProgressIndicator(),
              );
            },
          ),
        ),
        bottomNavigationBar: BottomNavigator(bottomNavIndex: 2));
  }

  Widget getPrograms(TrainingPlanBloc bloc) {
    return CustomScrollView(scrollDirection: Axis.vertical, slivers: [
      SliverGrid(
        delegate: SliverChildListDelegate([
          getTrainingPlan(t("My Active Training"), "asset/image/exercise_plan_execute.jpg", "",
              color: Colors.yellow[400]!, route: "myTrainingPlanExecute"),
          getTrainingPlan(t("My Custom Plan"), "asset/image/exercise_plan_custom.jpg", "",
              color: Colors.green[100]!, route: "myTrainingPlanCustom"),
          getTrainingPlan(t("Training Plans for Beginners"), "asset/menu/training_plans_q_beginner.jpg", "beginner"),
          getTrainingPlan(t("Training Plans for Home"), "asset/menu/training_plans_q_home.jpg", "home"),
          getTrainingPlan(t("Training Plans Advanced"), "asset/menu/training_plans_q_advanced.jpg", "advanced"),
          getTrainingPlan(t("Training Plans for Women"), "asset/menu/training_plans_q_woman.jpg", "for_woman"),
          getTrainingPlan(t("Training Plans of Celebrities"), "asset/menu/training_plans_q_celebrities.jpg", "celebrities"),
          getTrainingPlan(t("Training Plans for Gain Strength"), "asset/menu/training_plans_q_gain_strength.jpg", "gain_strength"),
          getTrainingPlan(t("Training Plans for Muscle Endurance"), "asset/menu/muscle_strength_q.jpg", "muscle_endurance"),
          getTrainingPlan(t("Physical Prepare Program for Footgolfers"), "asset/menu/FG_2_edz.jpg", "footgolf"),
        ]),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 15.0,
          crossAxisSpacing: 15.0,
          childAspectRatio: 1.0,
        ),
      )
    ]);
  }

  Widget getTrainingPlan(String name, String imageUrl, String parentName,
      {Color color = Colors.white, String route = "myTrainingPlanActivate"}) {
    double mediaWidth = MediaQuery.of(context).size.width;
    double imageWidth = (mediaWidth - 45) / 2;

    return ImageButton(
      width: imageWidth,
      textAlignment: Alignment.topLeft,
      text: name,
      style: GoogleFonts.robotoMono(
          textStyle: TextStyle(fontSize: 12, color: color, fontWeight: FontWeight.bold, backgroundColor: Colors.black54.withOpacity(0.4))),
      image: imageUrl,
      left: 5,
      textColor: color,
      onTap: () {
        Track().track(TrackingEvent.training_plan_open, eventValue: route);
        if (route == "myTrainingPlanActivate") {
          HashMap<String, dynamic> args = HashMap();
          args['parentName'] = parentName;
          Navigator.of(context).pushNamed(route, arguments: args);
        } else if (route == "myTrainingPlanExecute") {
          if (Cache().userLoggedIn != null) {
            final TrainingPlanBloc bloc = BlocProvider.of<TrainingPlanBloc>(context);
            bloc.setMyPlan(Cache().myTrainingPlan);
            Navigator.of(context).pushNamed(route);
          } else {
            showDialog(
                context: context,
                builder: (BuildContext context) {
                  return DialogCommon(
                    warning: true,
                    title: t("Warning"),
                    descriptions: t("Please log in"),
                    description2: t("because only in that way can you begin to execute a training plan"),
                    text: "OK",
                    onTap: () => Navigator.of(context).pushNamed("login"),
                    onCancel: () => {
                      Navigator.of(context).pop(),
                    },
                  );
                });
          }
        } else {
          Navigator.of(context).pushNamed(route);
        }
      },
      isLocked: false,
    );
  }
}