import 'dart:collection';

import 'package:aitrainer_app/bloc/account/account_bloc.dart';
import 'package:aitrainer_app/bloc/customer_change/customer_change_bloc.dart';
import 'package:aitrainer_app/library/custom_icon_icons.dart';
import 'package:aitrainer_app/library/dropdown_search/dropdown_search.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/sport.dart';
import 'package:aitrainer_app/util/app_language.dart';
import 'package:aitrainer_app/util/enums.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar_min.dart';
import 'package:aitrainer_app/widgets/app_bar_progress.dart';
import 'package:aitrainer_app/widgets/number_picker.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';
import 'package:syncfusion_flutter_gauges/gauges.dart';

import 'package:toggle_switch/toggle_switch.dart';

import '../library_keys.dart';

// ignore: must_be_immutable
class CustomerModifyPage extends StatelessWidget with Trans {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  bool fulldata = false;

  @override
  Widget build(BuildContext context) {
    setContext(context);
    dynamic arguments = ModalRoute.of(context)!.settings.arguments;
    if (arguments is HashMap && arguments['personal_data'] != null) {
      fulldata = arguments['personal_data'];
    }

    // ignore: close_sinks
    final accountBloc = BlocProvider.of<AccountBloc>(context);

    return BlocProvider(
        create: (context) => CustomerChangeBloc(customerRepository: accountBloc.customerRepository)..add(CustomerLoad()),
        child: Builder(builder: (context) {
          // ignore: close_sinks
          final customerBloc = BlocProvider.of<CustomerChangeBloc>(context);

          PreferredSizeWidget _bar = AppBarMin(
            back: true,
          );
          if (!fulldata) {
            _bar = AppBarProgress(max: 25, min: 0);
          }

          return Scaffold(
            resizeToAvoidBottomInset: true,
            appBar: _bar,
            body: Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('asset/image/WT_light_background.jpg'),
                    fit: BoxFit.fill,
                    alignment: Alignment.center,
                  ),
                ),
                child: BlocConsumer<CustomerChangeBloc, CustomerChangeState>(
                  listener: (context, state) {
                    if (state is CustomerSaveError) {
                      ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(backgroundColor: Colors.orange, content: Text(t(state.message), style: TextStyle(color: Colors.white))));
                    } else if (state is CustomerSaveSuccess) {
                      if (fulldata) {
                        Navigator.of(context).pop();
                      } else {
                        Navigator.of(context).pushNamed("customerGoalPage", arguments: customerBloc.customerRepository);
                      }
                    }
                  },
                  builder: (context, state) {
                    return ModalProgressHUD(
                      child: loadForm(customerBloc),
                      inAsyncCall: state is CustomerChangeLoading,
                      opacity: 0.5,
                      color: Colors.black54,
                      progressIndicator: CircularProgressIndicator(),
                    );
                  },
                )),
            floatingActionButton: FloatingActionButton.extended(
              onPressed: () => {
                //changingViewModel.saveCustomer(),
                customerBloc.add(CustomerSave()),
                //Navigator.of(context).pop(),
                //if (!fulldata) {Navigator.of(context).pushNamed("customerFitnessPage", arguments: customerBloc.customerRepository)}
              },
              backgroundColor: Colors.orange[600],
              icon: Icon(
                CustomIcon.save,
                size: 20,
              ),
              label: Text(
                fulldata ? t("Save") : t("Next"),
                style: GoogleFonts.inter(fontWeight: FontWeight.bold, fontSize: 12),
              ),
            ),
          );
        }));
  }

  Widget loadForm(CustomerChangeBloc customerBloc) {
    double mediaWidth = MediaQuery.of(context).size.width * .4;
    double mediaHeight = MediaQuery.of(context).size.height * .4;
    return Form(
      key: _scaffoldKey,
      child: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        padding: EdgeInsets.only(top: 40, left: 25, right: 25, bottom: 250),
        child: Container(
          alignment: Alignment.center,
          child: Column(
            children: [
              Text(t("Edit Profile"), style: GoogleFonts.archivoBlack(color: Colors.indigo, fontSize: 20), textAlign: TextAlign.center),
              Divider(
                color: Colors.transparent,
              ),
              Cache().getLoginType() == LoginType.email || fulldata
                  ? TextFormField(
                      key: LibraryKeys.loginEmailField,
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.only(left: 15, top: 15, bottom: 15),
                        labelText: t('Email'),
                        fillColor: Colors.white24,
                        filled: true,
                        border: OutlineInputBorder(
                          gapPadding: 4.0,
                          borderRadius: BorderRadius.circular(12.0),
                          borderSide: BorderSide(color: Colors.green[50]!, width: 0.4),
                        ),
                      ),
                      initialValue: customerBloc.customerRepository.customer!.email,
                      autovalidateMode: AutovalidateMode.onUserInteraction,
                      validator: (val) {
                        String? validator = customerBloc.emailValidation(val);
                        return validator == null ? null : t(validator);
                      },
                      keyboardType: TextInputType.emailAddress,
                      style: new TextStyle(fontSize: 16, color: Colors.indigo),
                      onChanged: (value) => {customerBloc.add(CustomerEmailChange(email: value))})
                  : Offstage(),
              Divider(
                color: Colors.transparent,
              ),
              Divider(
                color: Colors.transparent,
              ),
              Cache().getLoginType() != LoginType.apple || fulldata
                  ? TextFormField(
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.only(left: 15, top: 15, bottom: 15),
                        labelText: t('Name'),
                        fillColor: Colors.white24,
                        filled: true,
                        border: OutlineInputBorder(
                          gapPadding: 1.0,
                          borderRadius: BorderRadius.circular(12.0),
                          borderSide: BorderSide(color: Colors.green[50]!, width: 0.4),
                        ),
                      ),
                      initialValue: customerBloc.customerRepository.customer!.name,
                      autovalidateMode: AutovalidateMode.onUserInteraction,
                      validator: (val) {
                        String? validator = customerBloc.nameValidation(val);
                        return validator == null ? null : t(validator);
                      },
                      keyboardType: TextInputType.name,
                      style: new TextStyle(fontSize: 16, color: Colors.indigo),
                      onChanged: (value) => {customerBloc.add(CustomerNameChange(name: value))})
                  : Offstage(),
              Divider(
                color: Colors.transparent,
              ),
              Cache().getLoginType() != LoginType.apple || fulldata
                  ? TextFormField(
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.only(left: 15, top: 15, bottom: 15),
                        labelText: t('First Name'),
                        fillColor: Colors.white24,
                        filled: true,
                        border: OutlineInputBorder(
                          gapPadding: 2.0,
                          borderRadius: BorderRadius.circular(12.0),
                          borderSide: BorderSide(color: Colors.green[50]!, width: 0.4),
                        ),
                      ),
                      initialValue: customerBloc.customerRepository.customer!.firstname,
                      autovalidateMode: AutovalidateMode.onUserInteraction,
                      validator: (val) {
                        String? validator = customerBloc.nameValidation(val);
                        return validator == null ? null : t(validator);
                      },
                      keyboardType: TextInputType.name,
                      style: new TextStyle(fontSize: 16, color: Colors.indigo),
                      onChanged: (value) => {customerBloc.add(CustomerFirstNameChange(firstName: value))})
                  : Offstage(),
              Divider(
                color: Colors.transparent,
              ),
              Container(
                padding: EdgeInsets.only(left: 15),
                decoration: BoxDecoration(
                    color: Colors.white24,
                    border: Border.all(color: Colors.black, width: 0.4),
                    borderRadius: BorderRadius.all(Radius.circular(12))),
                child: Column(children: [
                  Text(t("Birth Year"),
                      style: GoogleFonts.inter(
                        fontWeight: FontWeight.normal,
                        fontSize: 18,
                      )),
                  SizedBox(
                    height: 20,
                  ),
                  SfLinearGauge(
                      minimum: 1950,
                      maximum: 2020,
                      labelPosition: LinearLabelPosition.outside,
                      tickPosition: LinearElementPosition.outside,
                      markerPointers: [
                        LinearWidgetPointer(
                          value: customerBloc.year!.toDouble(),
                          offset: 5,
                          position: LinearElementPosition.outside,
                          markerAlignment: LinearMarkerAlignment.center,
                          child: Container(
                            height: 14,
                            width: 44,
                            color: Colors.transparent,
                            child: Text(customerBloc.year!.toString(),
                                style: GoogleFonts.inter(
                                  fontSize: 12,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.indigo,
                                )),
                          ),
                        ),
                        LinearShapePointer(
                          value: customerBloc.year!.toDouble(),
                          position: LinearElementPosition.inside,
                          shapeType: LinearShapePointerType.triangle,
                          color: Colors.blue,
                          height: 55,
                          width: 25,
                          onChanged: (value) => {
                            customerBloc.add(CustomerBirthYearChange(year: value.toInt())),
                          },
                        ),
                      ],
                      orientation: LinearGaugeOrientation.horizontal,
                      majorTickStyle: LinearTickStyle(length: 20),
                      axisLabelStyle: TextStyle(fontSize: 12.0, color: Colors.black),
                      axisTrackStyle: LinearAxisTrackStyle(
                          color: Colors.cyan, edgeStyle: LinearEdgeStyle.bothFlat, thickness: 1.0, borderColor: Colors.grey)),
                  SizedBox(
                    height: 20,
                  ),
                ]),
              ),
              Divider(
                color: Colors.transparent,
              ),
              Container(
                padding: EdgeInsets.only(left: 15),
                decoration: BoxDecoration(
                    color: Colors.white24,
                    border: Border.all(color: Colors.black, width: 0.4),
                    borderRadius: BorderRadius.all(Radius.circular(12))),
                child: Column(children: [
                  Text(t("Weight"),
                      style: GoogleFonts.inter(
                        fontWeight: FontWeight.normal,
                        fontSize: 18,
                      )),
                  Divider(
                    color: Colors.transparent,
                  ),
                  NumberPickerWidget(
                      minValue: 40,
                      maxValue: 150,
                      initalValue: customerBloc.weight.toInt(),
                      unit: t("kg"),
                      color: Colors.blue[800]!,
                      onChange: (value) => customerBloc.add(CustomerWeightChange(weight: value))),
                  Divider(
                    color: Colors.transparent,
                  ),
                ]),
              ),
              Divider(
                color: Colors.transparent,
              ),
              Container(
                padding: EdgeInsets.only(left: 15),
                decoration: BoxDecoration(
                    color: Colors.white24,
                    border: Border.all(color: Colors.black, width: 0.4),
                    borderRadius: BorderRadius.all(Radius.circular(12))),
                child: Column(children: [
                  Text(t("Height"),
                      style: GoogleFonts.inter(
                        fontWeight: FontWeight.normal,
                        fontSize: 18,
                      )),
                  SizedBox(
                    height: 20,
                  ),
                  Row(
                    children: [
                      Cache().userLoggedIn!.sex == "m"
                          ? Image.asset(
                              "asset/image/test_picto_m.png",
                              height: mediaHeight,
                              width: mediaWidth,
                            )
                          : Image.asset(
                              "asset/image/test_picto_w.png",
                              height: mediaHeight,
                              width: mediaWidth,
                            ),
                      SfLinearGauge(
                          minimum: 140,
                          maximum: 220,
                          markerPointers: [
                            LinearWidgetPointer(
                              value: customerBloc.height,
                              offset: 5,
                              position: LinearElementPosition.inside,
                              markerAlignment: LinearMarkerAlignment.center,
                              child: Container(
                                height: 25,
                                width: 55,
                                color: Colors.transparent,
                                child: Text(customerBloc.height.toString(),
                                    style: GoogleFonts.inter(
                                      fontSize: 12,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.indigo,
                                    )),
                              ),
                            ),
                            LinearShapePointer(
                              height: 25,
                              width: 55,
                              color: Colors.blue,
                              value: customerBloc.height,
                              onChanged: (value) => {
                                customerBloc.add(CustomerHeightChange(height: value.toInt())),
                              },
                            ),
                          ],
                          orientation: LinearGaugeOrientation.vertical,
                          majorTickStyle: LinearTickStyle(length: 20),
                          axisLabelStyle: TextStyle(fontSize: 12.0, color: Colors.black),
                          axisTrackStyle: LinearAxisTrackStyle(
                              color: Colors.cyan, edgeStyle: LinearEdgeStyle.bothFlat, thickness: 1.0, borderColor: Colors.grey)),
                    ],
                  ),
                  SizedBox(
                    height: 20,
                  ),
                ]),
              ),
              Divider(
                color: Colors.transparent,
              ),
              ToggleSwitch(
                minWidth: 80.0,
                minHeight: 50.0,
                fontSize: 14.0,
                initialLabelIndex: customerBloc.customerRepository.customer!.sex == "m" ? 0 : 1,
                activeBgColor: Colors.indigo,
                activeFgColor: Colors.white,
                inactiveBgColor: Colors.white30,
                inactiveFgColor: Colors.grey[900],
                labels: [t('Man'), t('Woman')],
                onToggle: (index) {
                  customerBloc.add(CustomerGenderChange(gender: index));
                },
              ),
              Divider(),
              Divider(),
              Text(
                t("Your Primary Sport") + ":",
                textAlign: TextAlign.center,
                style: GoogleFonts.archivoBlack(
                  color: Colors.orange,
                  fontSize: 20,
                ),
              ),
              getSport(customerBloc),
              Divider(),
            ],
          ),
        ),
      ),
    );
  }

  Widget getSport(CustomerChangeBloc bloc) {
    Sport? selected = bloc.selectedSport;

    return Container(
        padding: EdgeInsets.only(left: 65, right: 65),
        child: DropdownSearch<Sport>(
          dropdownSearchDecoration: InputDecoration(
            contentPadding: EdgeInsets.only(left: 15, top: 5, bottom: 5),
            labelText: t("Sport"),
            labelStyle: GoogleFonts.inter(fontSize: 16, color: Colors.indigo),
            //fillColor: Colors.black38,
            filled: false,
            border: OutlineInputBorder(
              gapPadding: 2.0,
              borderRadius: BorderRadius.circular(12.0),
              borderSide: BorderSide(color: Colors.blue, width: 0.4),
            ),
          ),
          mode: Mode.MENU,
          compareFn: (Sport? i, Sport? s) {
            if (i == null || s == null) {
              return false;
            } else {
              return i.sportId == s.sportId;
            }
          },
          showSelectedItem: true,
          selectedItem: selected,
          itemAsString: (data) => data!.nameTranslations[AppLanguage().appLocal.toString()] != null
              ? data.nameTranslations[AppLanguage().appLocal.toString()]!
              : data.name,
          onChanged: (data) {
            bloc.add(CustomerSportChange(sport: data!));
          },
          dropdownBuilder: _customDropDownItem,
          popupItemBuilder: _customMenuBuilder,
          popupBarrierColor: Colors.white10,
          //popupBackgroundColor: Colors.yellow,
          items: Cache().getSports(),
          dropDownButton: Icon(
            Icons.arrow_drop_down,
            color: Colors.indigo,
          ),
        ));
    //items: FitnessItem().toList()));
  }

  Widget _customMenuBuilder(BuildContext context, Sport? sport, bool isSelected) {
    return Container(
      decoration: !isSelected
          ? BoxDecoration(color: Colors.grey[300])
          : BoxDecoration(
              border: Border.all(color: Colors.blue),
              borderRadius: BorderRadius.circular(12),
              color: Colors.grey[100],
            ),
      child: ListTile(
        selected: isSelected,
        title: Text(
          sport!.nameTranslations[AppLanguage().appLocal.toString()] != null
              ? sport.nameTranslations[AppLanguage().appLocal.toString()]!
              : sport.name,
          style: GoogleFonts.archivoBlack(fontSize: 20, color: Colors.blue[600]),
        ),
        subtitle: Text(
          sport.name,
          style: GoogleFonts.inter(fontSize: 12, color: Colors.blue[600]),
        ),
      ),
    );
  }

  Widget _customDropDownItem(BuildContext context, Sport? item, String itemDesignation) {
    return Container(
      child: (item == null)
          ? ListTile(
              contentPadding: EdgeInsets.all(0),
              title: Text(
                t("No item selected"),
                style: GoogleFonts.inter(fontSize: 14, color: Colors.blue[600]),
              ),
            )
          : ListTile(
              contentPadding: EdgeInsets.all(0),
              title: Text(
                item.nameTranslations[AppLanguage().appLocal.toString()] != null
                    ? item.nameTranslations[AppLanguage().appLocal.toString()]!
                    : item.name,
                style: GoogleFonts.archivoBlack(fontSize: 20, color: Colors.blue[600]),
              ),
              subtitle: Text(
                item.name,
                style: GoogleFonts.inter(fontSize: 12, color: Colors.blue[600]),
              ),
            ),
    );
  }
}