import 'package:driverapp/app-icons/driver_app_icons.dart';
import 'package:driverapp/config/size_config.dart';
import 'package:driverapp/core/model/authentication/login_request.dart';
import 'package:driverapp/core/viewModels/authentication_view_model.dart';
import 'package:driverapp/core/viewModels/project_view_model.dart';
import 'package:driverapp/pages/authentication/reset_password_page.dart';
import 'package:driverapp/uitl/translations_delegate_base.dart';
import 'package:driverapp/uitl/utils.dart';
import 'package:driverapp/widgets/buttons/secondary_button.dart';
import 'package:driverapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';

import 'forget_password_page.dart';

// ignore: must_be_immutable
class VerificationPage extends StatelessWidget {
  LoginRequest loginRequest = LoginRequest();
  final loginFormKey = GlobalKey<FormState>();
  ProjectViewModel projectViewModel;
  AuthenticationViewModel authenticationViewModel;
  final verifyAccountForm = GlobalKey<FormState>();

  Map verifyAccountFormValue = {
    'digit1': null,
    'digit2': null,
    'digit3': null,
    'digit4': null,
  };

  FocusNode focusD1 = FocusNode();
  FocusNode focusD2 = FocusNode();
  FocusNode focusD3 = FocusNode();
  FocusNode focusD4 = FocusNode();
  var model;
  TextEditingController digit1 = TextEditingController(text: "");
  TextEditingController digit2 = TextEditingController(text: "");
  TextEditingController digit3 = TextEditingController(text: "");
  TextEditingController digit4 = TextEditingController(text: "");

  login() async {
    if (loginFormKey.currentState.validate()) {
      loginFormKey.currentState.save();
      await authenticationViewModel.login(loginRequest);
      if (authenticationViewModel.isError) {
        Utils.showErrorToast(authenticationViewModel.error);
      }
    }
  }

  SizedBox buildSizedBox([double height = 20]) {
    return SizedBox(
      height: height,
    );
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    authenticationViewModel = Provider.of(context);
    // focusD1 = FocusNode();
    // focusD2 = FocusNode();
    // focusD3 = FocusNode();
    // focusD4 = FocusNode();

    String validateCodeDigit(value) {
      if (value.isEmpty) {
        return 'Please enter your Password';
      }

      return null;
    }

    return AnimatedSwitcher(
      duration: Duration(microseconds: 350),
      child: AppScaffold(
        isShowAppBar: false,
        body: SingleChildScrollView(
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                FractionallySizedBox(
                  widthFactor: 0.80,
                  child: Column(
                    children: <Widget>[
                      SizedBox(
                        height: MediaQuery.of(context).size.height * 0.25,
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            child: Icon(
                              DriverApp.exclamation_mark,
                              size: 150,
                              color: Theme.of(context).primaryColor,
                            ),
                            margin: EdgeInsets.only(
                              top: 20,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Column(
                        children: <Widget>[
                          Center(
                            child: Text(
                              "Verification",
                              style: TextStyle(
                                  fontSize: 25,
                                  letterSpacing: 1,
                                  fontWeight: FontWeight.w600),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 30,
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Form(
                          key: verifyAccountForm,
                          child: Container(
                              width: SizeConfig.realScreenWidth * 0.90,
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Padding(
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 20),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.end,
                                        children: <Widget>[
                                          Expanded(
                                            child: Text(
                                              TranslationBase.of(context)
                                                  .enterVerificationMsg,
                                              style: TextStyle(
                                                  fontSize: 13,
                                                  color: Colors.grey),
                                            ),
                                          ),
                                          SizedBox(
                                            height: 10,
                                          )
                                        ],
                                      ),
                                    ),
                                    buildSizedBox(30),
                                    Center(
                                      child: FractionallySizedBox(
                                        widthFactor: 0.80,
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceAround,
                                          children: <Widget>[
                                            Container(
                                              width: 55,
                                              height: 55,
                                              color: Colors.white,
                                              child: TextFormField(
                                                textInputAction:
                                                    TextInputAction.next,
                                                style: TextStyle(
                                                  fontSize: SizeConfig
                                                          .textMultiplier *
                                                      3,
                                                ),
                                                focusNode: focusD1,
                                                controller: digit1,
                                                textAlign: TextAlign.center,
                                                keyboardType:
                                                    TextInputType.number,
                                                decoration:
                                                    buildInputDecoration(
                                                        context),
                                                onSaved: (val) {
                                                  verifyAccountFormValue[
                                                      'digit1'] = val;
                                                },
                                                validator: validateCodeDigit,
                                                onFieldSubmitted: (_) {
                                                  FocusScope.of(context)
                                                      .requestFocus(focusD2);
                                                },
                                                onChanged: (val) {
                                                  if (val.length == 1) {
                                                    FocusScope.of(context)
                                                        .requestFocus(focusD2);
                                                  }
                                                },
                                              ),
                                            ),
                                            Container(
                                              width: 55,
                                              height: 55,
                                              color: Colors.white,
                                              child: TextFormField(
                                                focusNode: focusD2,
                                                controller: digit2,
                                                textInputAction:
                                                    TextInputAction.next,
                                                textAlign: TextAlign.center,
                                                style: TextStyle(
                                                  fontSize: SizeConfig
                                                          .textMultiplier *
                                                      3,
                                                ),
                                                keyboardType:
                                                    TextInputType.number,
                                                decoration:
                                                    buildInputDecoration(
                                                        context),
                                                validator: validateCodeDigit,
                                                onSaved: (val) {
                                                  verifyAccountFormValue[
                                                      'digit2'] = val;
                                                },
                                                onFieldSubmitted: (_) {
                                                  FocusScope.of(context)
                                                      .requestFocus(focusD3);
                                                },
                                                onChanged: (val) {
                                                  if (val.length == 1) {
                                                    FocusScope.of(context)
                                                        .requestFocus(focusD3);
                                                  }
                                                },
                                              ),
                                            ),
                                            Container(
                                                width: 55,
                                                height: 55,
                                                color: Colors.white,
                                                child: TextFormField(
                                                  focusNode: focusD3,
                                                  controller: digit3,
                                                  textInputAction:
                                                      TextInputAction.next,
                                                  textAlign: TextAlign.center,
                                                  style: TextStyle(
                                                    fontSize: SizeConfig
                                                            .textMultiplier *
                                                        3,
                                                  ),
                                                  keyboardType:
                                                      TextInputType.number,
                                                  decoration:
                                                      buildInputDecoration(
                                                          context),
                                                  validator: validateCodeDigit,
                                                  onSaved: (val) {
                                                    verifyAccountFormValue[
                                                        'digit3'] = val;
                                                  },
                                                  onFieldSubmitted: (_) {
                                                    FocusScope.of(context)
                                                        .requestFocus(focusD4);
                                                  },
                                                  onChanged: (val) {
                                                    if (val.length == 1) {
                                                      FocusScope.of(context)
                                                          .requestFocus(
                                                              focusD4);
                                                    }
                                                  },
                                                )),
                                            Container(
                                              width: 55,
                                              height: 55,
                                              color: Colors.white,
                                              child: TextFormField(
                                                  focusNode: focusD4,
                                                  controller: digit4,
                                                  textAlign: TextAlign.center,
                                                  style: TextStyle(
                                                    fontSize: SizeConfig
                                                            .textMultiplier *
                                                        3,
                                                  ),
                                                  keyboardType:
                                                      TextInputType.number,
                                                  decoration:
                                                      buildInputDecoration(
                                                          context),
                                                  validator: validateCodeDigit,
                                                  onSaved: (val) {
                                                    verifyAccountFormValue[
                                                        'digit4'] = val;
                                                  },
                                                  onFieldSubmitted: (_) {
                                                    FocusScope.of(context)
                                                        .requestFocus(focusD4);
                                                    submit(model, context);
                                                  },
                                                  onChanged: (val) {
                                                    if (val.length == 1) {
                                                      FocusScope.of(context)
                                                          .requestFocus(
                                                              focusD4);
                                                      submit(model, context);
                                                    }
                                                  }),
                                            )
                                          ],
                                        ),
                                      ),
                                    ),
                                    buildSizedBox(20),
                                    // ShowTimerText(model: model),
                                  ])))
                    ],
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                SizedBox(
                  height: 10,
                ),
                Container(
                    margin: EdgeInsets.all(10),
                    height: MediaQuery.of(context).size.height * 0.22,
                    child: Column(
                      children: <Widget>[
                        SecondaryButton(
                          label: "Verify",
                          onTap: () {
                            submit(model, context);
                          },
                          disabled: authenticationViewModel.isLoading,
                          loading: authenticationViewModel.isLoading,
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: <Widget>[
                            InkWell(
                              onTap: () {
                                Navigator.pushReplacement(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          ForgetPasswordPage()),
                                );
                              },
                              child: InkWell(
                                onTap: () async {
                                  await authenticationViewModel
                                      .getOpt(authenticationViewModel.userId);
                                },
                                child: Text(
                                  "Resend OPT?",
                                  style: TextStyle(
                                      fontSize: 14,
                                      color: Theme.of(context).primaryColor),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ))
              ],
            ),
          ),
        ),
      ),
    );
  }

  TextStyle buildTextStyle() {
    return TextStyle(
      fontSize: SizeConfig.textMultiplier * 3,
    );
  }

  InputDecoration buildInputDecoration(BuildContext context) {
    return InputDecoration(
      // ts/images/password_icon.png
      contentPadding: EdgeInsets.only(top: 30, bottom: 30),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10)),
        borderSide: BorderSide(color: Colors.black),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).primaryColor),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).errorColor),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).errorColor),
      ),
    );
  }

  void submit(AuthenticationViewModel model, BuildContext context) async {
    if (verifyAccountForm.currentState.validate()) {
      final activationCode =
          digit1.text + digit2.text + digit3.text + digit4.text;

      await authenticationViewModel
          .checkActivationCode(int.parse(activationCode));
      if (authenticationViewModel.isError) {
        Utils.showErrorToast(authenticationViewModel.error);
      } else {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => RestPasswordPage()),
        );
      }
    }
  }
}
