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/model/cache.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/cupertino.dart';
import 'package:flutter/widgets.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,
                          onValueChanged: (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,
                  ),
                  SfLinearGauge(
                      minimum: 40,
                      maximum: 150,
                      labelPosition: LinearLabelPosition.outside,
                      tickPosition: LinearElementPosition.outside,
                      markerPointers: [
                        LinearWidgetPointer(
                          value: customerBloc.weight,
                          offset: 5,
                          position: LinearElementPosition.outside,
                          markerAlignment: LinearMarkerAlignment.center,
                          child: Container(
                            height: 14,
                            width: 44,
                            color: Colors.transparent,
                            child: Text(customerBloc.weight.toStringAsFixed(1),
                                style: GoogleFonts.inter(
                                  fontSize: 12,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.indigo,
                                )),
                          ),
                        ),
                        LinearShapePointer(
                          position: LinearElementPosition.inside,
                          shapeType: LinearShapePointerType.triangle,
                          value: customerBloc.weight,
                          height: 55,
                          width: 25,
                          color: Colors.blue,
                          onValueChanged: (value) => {
                            customerBloc.add(CustomerWeightChange(weight: value)),
                          },
                        ),
                      ],
                      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)),
                  Divider(
                    color: Colors.transparent,
                  ),
                  /* SfRadialGauge(
                    axes: <RadialAxis>[
                      RadialAxis(
                        axisLineStyle: AxisLineStyle(
                          thickness: 0.1,
                          thicknessUnit: GaugeSizeUnit.factor,
                          gradient: const SweepGradient(colors: <Color>[Color(0xffb4f500), Colors.blue], stops: <double>[0.1, 0.9]),
                        ),
                        minimum: 40,
                        maximum: 160,
                        pointers: [
                          WidgetPointer(
                              value: customerBloc.weight.toDouble(),
                              child: Container(
                                height: 55,
                                width: 60,
                                color: Colors.transparent,
                                child: Text(customerBloc.weight.toStringAsFixed(1),
                                    style: GoogleFonts.inter(
                                      fontSize: 14,
                                      color: Colors.indigo,
                                    )),
                              )),
                          NeedlePointer(
                            needleColor: Colors.blue[200],
                            knobStyle: KnobStyle(color: Colors.blue[800]),
                            value: customerBloc.weight.toDouble(),
                            enableAnimation: true,
                            //enableDragging: true,
                            needleStartWidth: 1,
                            needleEndWidth: 12,
                            //onValueChanged: (value) => {customerBloc.add(CustomerWeightChange(weight: value))},
                          )
                        ],
                      )
                    ],
                  ), */
                ]),
              ),
              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,
                              onValueChanged: (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(),
              /* TextButton(
                onPressed: () => {customerBloc.add(CustomerSave())},
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Image.asset('asset/icon/gomb_orange_a.png', width: 140, height: 60),
                    Text(
                      fulldata ? t("Save") : t("Next"),
                      style: TextStyle(fontSize: 16, color: Colors.white),
                    ),
                  ],
                ),
              ), */
            ],
          ),
        ),
      ),
    );
  }
}
