import 'package:aitrainer_app/bloc/customer_exercise_device/customer_exercise_device_bloc.dart';
import 'package:aitrainer_app/util/app_language.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/exercise_device.dart';
import 'package:aitrainer_app/repository/customer_exercise_device_repository.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar.dart';
import 'package:aitrainer_app/widgets/image_button.dart';
import 'package:flutter/cupertino.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 CustomerExerciseDevicePage extends StatelessWidget with Trans {
  late List<Widget> listDevice;

  @override
  Widget build(BuildContext context) {
    setContext(context);
    double cWidth = MediaQuery.of(context).size.width;
    double cHeight = MediaQuery.of(context).size.height;
    return Scaffold(
        appBar: AppBarNav(depth: 0),
        body: Container(
            padding: EdgeInsets.all(10),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('asset/image/WT_black_background.jpg'),
                fit: BoxFit.cover,
                alignment: Alignment.center,
              ),
            ),
            child: BlocProvider(
                create: (context) =>
                    CustomerExerciseDeviceBloc(repository: CustomerExerciseDeviceRepository(), devices: Cache().getDevices()!)
                      ..add(CustomerExerciseDeviceLoad()),
                child: BlocConsumer<CustomerExerciseDeviceBloc, CustomerExerciseDeviceState>(
                  listener: (context, state) {
                    if (state is CustomerExerciseDeviceError) {
                      ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white))));
                    }
                  },
                  builder: (context, state) {
                    final bloc = BlocProvider.of<CustomerExerciseDeviceBloc>(context);
                    return ModalProgressHUD(
                      child: getPage(bloc, cWidth, cHeight),
                      inAsyncCall: state is CustomerExerciseDeviceLoading,
                      opacity: 0.5,
                      color: Colors.black54,
                      progressIndicator: CircularProgressIndicator(),
                    );
                  },
                ))));
  }

  Widget getPage(CustomerExerciseDeviceBloc bloc, double cWidth, double cHeight) {
    //print("width" + cWidth.toString());
    return CustomScrollView(scrollDirection: Axis.vertical, slivers: [
      SliverGrid(
        delegate: SliverChildListDelegate([
          Text(t("Available Training Places"),
              textAlign: TextAlign.center,
              maxLines: 2,
              softWrap: true,
              style: GoogleFonts.archivoBlack(
                fontSize: 24,
                color: Colors.white,
                shadows: <Shadow>[
                  Shadow(
                    offset: Offset(5.0, 5.0),
                    blurRadius: 12.0,
                    color: Colors.black54,
                  ),
                  Shadow(
                    offset: Offset(-3.0, 3.0),
                    blurRadius: 12.0,
                    color: Colors.black54,
                  ),
                ],
              )),
          Text(t("select your places by tapping"),
              textAlign: TextAlign.center,
              softWrap: true,
              maxLines: 2,
              style: GoogleFonts.archivoBlack(
                fontSize: 14,
                color: Colors.white,
                shadows: <Shadow>[
                  Shadow(
                    offset: Offset(5.0, 5.0),
                    blurRadius: 12.0,
                    color: Colors.black54,
                  ),
                  Shadow(
                    offset: Offset(-3.0, 3.0),
                    blurRadius: 12.0,
                    color: Colors.black54,
                  ),
                ],
              )),
        ]),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1,
          mainAxisSpacing: 0.0,
          crossAxisSpacing: 0.0,
          childAspectRatio: cWidth > 375 ? 9.1 : 4.1,
        ),
      ),
      SliverGrid(
        delegate: SliverChildListDelegate(getDevicesPlace(bloc, cWidth, cHeight)),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1,
          mainAxisSpacing: 15.0,
          crossAxisSpacing: 5.0,
          childAspectRatio: 2.5,
        ),
      ),
      SliverGrid(
        delegate: SliverChildListDelegate([
          SizedBox(
            height: 1,
          ),
          Text(t("Available Equipments"),
              textAlign: TextAlign.center,
              maxLines: 2,
              style: GoogleFonts.archivoBlack(
                fontSize: 24,
                color: Colors.white,
                shadows: <Shadow>[
                  Shadow(
                    offset: Offset(5.0, 5.0),
                    blurRadius: 12.0,
                    color: Colors.black54,
                  ),
                  Shadow(
                    offset: Offset(-3.0, 3.0),
                    blurRadius: 12.0,
                    color: Colors.black54,
                  ),
                ],
              )),
          Text(t("select your equipments by tapping"),
              textAlign: TextAlign.center,
              maxLines: 2,
              style: GoogleFonts.archivoBlack(
                fontSize: 14,
                color: Colors.white,
                shadows: <Shadow>[
                  Shadow(
                    offset: Offset(5.0, 5.0),
                    blurRadius: 12.0,
                    color: Colors.black54,
                  ),
                  Shadow(
                    offset: Offset(-3.0, 3.0),
                    blurRadius: 12.0,
                    color: Colors.black54,
                  ),
                ],
              )),
        ]),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1,
          mainAxisSpacing: 2.0,
          crossAxisSpacing: 5.0,
          childAspectRatio: cWidth > 375 ? 9.1 : 6.1,
        ),
      ),
      SliverGrid(
        delegate: SliverChildListDelegate(getDevices(bloc, cWidth, cHeight)),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 15.0,
          crossAxisSpacing: 15.0,
          childAspectRatio: 1.0,
        ),
      ),
    ]);
  }

  List<Widget> getDevices(CustomerExerciseDeviceBloc bloc, double cWidth, double cHeight) {
    final bool isEnglish = AppLanguage().appLocal.languageCode == "en";
    this.listDevice = [];
    final devices = bloc.devices;
    if (devices != null) {
      devices.sort((a, b) => a.sort.compareTo(b.sort));
      devices.forEach((element) {
        if (element.place == false) {
          final String url = "asset/equipment/" + element.imageUrl.substring(7);
          ImageButton button = ImageButton(
            width: cWidth / 2 - 10,
            height: cWidth / 2 - 10,
            textAlignment: Alignment.topCenter,
            text: isEnglish ? element.name : element.nameTranslation,
            style: GoogleFonts.archivoBlack(fontSize: 14, color: Colors.white, backgroundColor: Colors.black54.withOpacity(0.4)),
            image: url,
            left: 5,
            onTap: () => changeButtonShape(element, bloc),
            isLocked: false,
            isMarked: bloc.hasCustomerDevice(element.exerciseDeviceId),
            buttonIndex: element.exerciseDeviceId,
            isShape: false,
          );
          listDevice.add(button);
        }
      });
    }
    return listDevice;
  }

  List<Widget> getDevicesPlace(CustomerExerciseDeviceBloc bloc, double cWidth, cHeight) {
    final bool isEnglish = AppLanguage().appLocal.languageCode == "en";
    this.listDevice = [];
    final devices = bloc.devices;
    if (devices != null) {
      devices.sort((a, b) => a.sort.compareTo(b.sort));
      devices.forEach((element) {
        if (element.place) {
          final String url = "asset/equipment/" + element.imageUrl.substring(7);
          ImageButton button = ImageButton(
            width: cWidth - 60,
            height: cWidth / 2 - 40,
            top: 10,
            textAlignment: Alignment.topCenter,
            text: isEnglish ? element.name : element.nameTranslation,
            style: GoogleFonts.archivoBlack(fontSize: 14, color: Colors.white, backgroundColor: Colors.black54.withOpacity(0.4)),
            image: url,
            left: 5,
            onTap: () => changeButtonShape(element, bloc),
            isLocked: false,
            buttonIndex: element.exerciseDeviceId,
            isShape: false,
            isMarked: bloc.hasCustomerDevice(element.exerciseDeviceId),
          );
          listDevice.add(button);
        }
      });
    }
    return listDevice;
  }

  void changeButtonShape(ExerciseDevice device, CustomerExerciseDeviceBloc bloc) {
    if (bloc.hasCustomerDevice(device.exerciseDeviceId)) {
      bloc.add(CustomerExerciseDeviceRemove(device: device));
    } else {
      bloc.add(CustomerExerciseDeviceAdd(device: device));
    }
  }
}