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/numberpicker.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: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/modal_progress_hud.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>();

  @override
  Widget build(BuildContext context) {
    setContext(context);
    // ignore: close_sinks
    final accountBloc = BlocProvider.of<AccountBloc>(context);

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

          return Scaffold(
              resizeToAvoidBottomInset: true,
              appBar: AppBarMin(
                back: true,
              ),
              body: Container(
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('asset/image/WT_light_background.png'),
                      fit: BoxFit.fill,
                      alignment: Alignment.center,
                    ),
                  ),
                  child: BlocConsumer<CustomerChangeBloc, CustomerChangeState>(
                    listener: (context, state) {
                      if (state is CustomerSaveError) {
                        String message = t(state.message);
                        if (message == null) {
                          message = "";
                        } else {
                          Scaffold.of(context).showSnackBar(
                              SnackBar(backgroundColor: Colors.orange, content: Text(message, style: TextStyle(color: Colors.white))));
                        }
                      } else if (state is CustomerSaveSuccess) {
                        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(),
                      );
                    },
                  )));
        }));
  }

  Widget loadForm(CustomerChangeBloc customerBloc) {
    return Form(
      key: _scaffoldKey,
      autovalidateMode: AutovalidateMode.always,
      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("Please provide us some personal data"),
                  style: GoogleFonts.inter(color: Colors.indigo, fontSize: 16), textAlign: TextAlign.center),
              Text(t("To lift your experience using the app"),
                  style: GoogleFonts.inter(color: Colors.orange[700], fontSize: 16), textAlign: TextAlign.center),
              Divider(
                color: Colors.transparent,
              ),
              Cache().getLoginType() == LoginType.email
                  ? 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.always,
                      validator: (val) {
                        return customerBloc.emailValidation(val);
                      },
                      keyboardType: TextInputType.emailAddress,
                      style: new TextStyle(fontSize: 16, color: Colors.indigo),
                    )
                  : Offstage(),
              Divider(
                color: Colors.transparent,
              ),
              Cache().getLoginType() == LoginType.email
                  ? TextFormField(
                      key: LibraryKeys.loginPasswordField,
                      obscureText: true,
                      decoration: InputDecoration(
                        labelStyle: TextStyle(fontSize: 14),
                        contentPadding: EdgeInsets.only(left: 15, top: 15, bottom: 15),
                        suffixIcon: IconButton(
                          onPressed: () => {customerBloc.add(CustomerChangePasswordObscure())},
                          icon: Icon(Icons.remove_red_eye),
                        ),
                        labelText: t('Password (Leave empty if no change)'),
                        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.password,
                      autovalidateMode: AutovalidateMode.always,
                      validator: (val) {
                        return customerBloc.passwordValidation(val);
                      },
                      keyboardType: TextInputType.visiblePassword,
                      style: new TextStyle(fontSize: 16, color: Colors.indigo),
                    )
                  : Offstage(),
              Divider(
                color: Colors.transparent,
              ),
              Cache().getLoginType() != LoginType.apple
                  ? 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.always,
                      validator: (val) {
                        return customerBloc.nameValidation(val);
                      },
                      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
                  ? 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.always,
                      validator: (val) {
                        return customerBloc.nameValidation(val);
                      },
                      keyboardType: TextInputType.name,
                      style: new TextStyle(fontSize: 16, color: Colors.indigo),
                      onChanged: (value) => {customerBloc.add(CustomerFirstNameChange(firstName: value))})
                  : Offstage(),
              Divider(
                color: Colors.transparent,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    flex: 4,
                    child: Text(t("Birth Year"), style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14)),
                  ),
                  Flexible(
                    fit: FlexFit.tight,
                    flex: 8,
                    child: NumberPicker.horizontal(
                      highlightSelectedValue: true,
                      initialValue: customerBloc.year,
                      minValue: 1930,
                      maxValue: 2100,

                      step: 1,
                      textStyle: TextStyle(fontWeight: FontWeight.bold),
                      textStyleHighlighted: TextStyle(fontSize: 16, color: Colors.indigo, fontWeight: FontWeight.bold),
                      onChanged: (value) => {customerBloc.add(CustomerBirthYearChange(year: value))},
                      listViewHeight: 60,
                      //decoration: _decoration,
                    ),
                  ),
                  SizedBox(width: 80),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Expanded(
                    flex: 4,
                    child: Text(t("Weight"), style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14)),
                  ),
                  Flexible(
                    fit: FlexFit.tight,
                    flex: 8,
                    child: NumberPicker.horizontal(
                      highlightSelectedValue: true,
                      initialValue: customerBloc.weight.toInt(),
                      minValue: 0,
                      maxValue: 200,
                      step: 1,
                      textStyle: TextStyle(fontWeight: FontWeight.bold),
                      textStyleHighlighted: TextStyle(fontSize: 18, color: Colors.indigo, fontWeight: FontWeight.bold),
                      onChanged: (value) => {customerBloc.add(CustomerWeightChange(weight: value))},
                      listViewHeight: 60,
                    ),
                  ),
                  SizedBox(width: 80),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Expanded(
                    flex: 4,
                    child: Text(t("Height"), style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14)),
                  ),
                  Flexible(
                    fit: FlexFit.tight,
                    flex: 8,
                    child: NumberPicker.horizontal(
                      highlightSelectedValue: true,
                      initialValue: customerBloc.height.toInt(),
                      minValue: 0,
                      maxValue: 230,
                      step: 1,
                      textStyle: TextStyle(fontWeight: FontWeight.bold),
                      textStyleHighlighted: TextStyle(fontSize: 18, color: Colors.indigo, fontWeight: FontWeight.bold),
                      onChanged: (value) => {customerBloc.add(CustomerHeightChange(height: value))},
                      listViewHeight: 60,
                    ),
                  ),
                  SizedBox(width: 80),
                ],
              ),
              Divider(),
              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(),
              FlatButton(
                onPressed: () => {customerBloc.add(CustomerSave())},
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Image.asset('asset/icon/gomb_orange_a.png', width: 140, height: 60),
                    Text(
                      t("Next"),
                      style: TextStyle(fontSize: 16, color: Colors.white),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void showInSnackBar(String error) {
    _scaffoldKey.currentState
        .showSnackBar(SnackBar(backgroundColor: Colors.orange, content: Text(error, style: TextStyle(color: Colors.white))));
  }
}