import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:async';

import 'package:numeric_keyboard/numeric_keyboard.dart';
import 'package:pin_code_fields/pin_code_fields.dart';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:i18n_translate/i18n.dart';
import 'package:{{ name }}/repository/AuthenticationRepository.dart';
import 'package:{{ name }}/bloc/blocs.dart';

class AuthOtp extends StatelessWidget {
  final AuthenticationRepository authenticationRepository;

  AuthOtp({Key key, @required this.authenticationRepository})
      : assert(authenticationRepository != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocProvider(
        create: (context) {
          return OtpBloc(
            authenticationRepository: authenticationRepository,
          );
        },
        child: AuthOtpForm(),
      ),
    );
  }
}

class AuthOtpForm extends StatefulWidget {
  @override
  State<AuthOtpForm> createState() => _AuthOtpFormState();
}

class _AuthOtpFormState extends State<AuthOtpForm> {
  final _otpController = TextEditingController();

  StreamController<ErrorAnimationType> errorController;

  bool hasError = false;
  String currentText = "";

  @override
  void initState() {
    errorController = StreamController<ErrorAnimationType>();
    super.initState();
  }

  @override
  void dispose() {
    errorController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    
    _onOtpButtonPressed() {
      if (currentText.length != 6 || currentText != "towtow") {
        errorController
            .add(ErrorAnimationType.shake); // Triggering error shake animation
        setState(() {
          hasError = true;
        });
      } else {
        setState(() {
          hasError = false;
          BlocProvider.of<OtpBloc>(context).add(
            OtpSendButtonPressed(
              otp: _otpController.text,
            ),
          );
        });
      }
    }

    void _onKeyboardTap(String value) {
      setState(() {
        _otpController.text = _otpController.text + value;
      });
    }

    return BlocListener<OtpBloc, OtpState>(
      listener: (context, state) {
        if (state is OtpFailure) {
          Scaffold.of(context).showSnackBar(
            SnackBar(
              content: Text('${state.error}'),
              backgroundColor: Colors.red,
            ),
          );
        }
        if (state is OtpSuccces) {
          Navigator.of(context)
              .pushNamedAndRemoveUntil('/', (Route<dynamic> route) => false);
        }
      },
      child: BlocBuilder<OtpBloc, OtpState>(
        builder: (context, state) {
          return LayoutBuilder(builder: (context, constraints) {
            return SingleChildScrollView(
              child: ConstrainedBox(
                constraints: BoxConstraints(
                    minWidth: constraints.maxWidth,
                    minHeight: constraints.maxHeight),
                child: IntrinsicHeight(
                  child: Padding(
                    padding:
                        EdgeInsets.symmetric(horizontal: 15.0, vertical: 30.0),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.max,
                        children: [
                          BackButton(
                            color: Colors.grey,
                            onPressed: () => Navigator.pop(context),
                          ),
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 15.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisSize: MainAxisSize.max,
                              children: <Widget>[
                                SizedBox(height: 15.0),
                                Text(
                                    I18n.translate(
                                        context, 'otp.phone_verification'),
                                    style: TextStyle(
                                      color: Color(0xff182779),
                                      fontFamily: 'CM Sans Serif',
                                      fontWeight: FontWeight.bold,
                                      fontSize: 32.0,
                                      height: 1.5,
                                    )),
                                SizedBox(height: 15.0),
                                RichText(
                                  text: TextSpan(
                                      text: I18n.translate(context, 'otp.msg'),
                                      children: [
                                        TextSpan(
                                            text: " +526366976925",
                                            style: TextStyle(
                                                color: Color(0xFF182779),
                                                fontWeight: FontWeight.bold,
                                                fontSize: 15)),
                                      ],
                                      style: TextStyle(
                                        color: Color(0xFF182779),
                                        fontSize: 16.0,
                                        height: 1.2,
                                      )),
                                ),
                                SizedBox(height: 30.0),
                                PinCodeTextField(
                                  length: 6,
                                  backgroundColor: Colors.transparent,
                                  obsecureText: false,
                                  animationType: AnimationType.fade,
                                  pinTheme: PinTheme(
                                    shape: PinCodeFieldShape.box,
                                    borderRadius: BorderRadius.circular(8),
                                    borderWidth: 1.0,
                                    fieldHeight: 50,
                                    fieldWidth: 40,
                                    inactiveFillColor: Color(0xffe9e9e9),
                                    inactiveColor: Color(0xffe9e9e9),
                                    activeColor: Color(0xff0251ff),
                                    activeFillColor:
                                        hasError ? Colors.orange : Colors.white,
                                  ),
                                  animationDuration:
                                      Duration(milliseconds: 300),
                                  enableActiveFill: true,
                                  errorAnimationController: errorController,
                                  controller: _otpController,
                                  onCompleted: (v) {
                                    print("Completed");
                                    _onOtpButtonPressed();
                                  },
                                  onChanged: (value) {
                                    print(value);
                                    setState(() {
                                      currentText = value;
                                    });
                                  },
                                  beforeTextPaste: (text) {
                                    print("Allowing to paste $text");
                                    //if you return true then it will show the paste confirmation dialog. Otherwise if false, then nothing will happen.
                                    //but you can show anything you want here, like your pop up saying wrong paste format or etc
                                    return true;
                                  },
                                ),
                                SizedBox(
                                  height: 20,
                                ),
                                RichText(
                                  textAlign: TextAlign.center,
                                  text: TextSpan(
                                      text: "Didn't receive the code? ",
                                      style: TextStyle(
                                          color: Colors.black54, fontSize: 15),
                                      children: [
                                        TextSpan(
                                            text: " RESEND",
                                            //recognizer: onTapRecognizer,
                                            style: TextStyle(
                                                color: Color(0xff182779),
                                                fontWeight: FontWeight.bold,
                                                fontSize: 16))
                                      ]),
                                ),
                              ],
                            ),
                          ),
                          Expanded(
                            child: Container(),
                          ),
                          NumericKeyboard(
                            onKeyboardTap: _onKeyboardTap,
                            textColor: Color(0xFF182779),
                            rightIcon: Icon(
                              Icons.backspace,
                              color: Color(0xFF182779),
                            ),
                            rightButtonFn: () {
                              setState(() {
                                _otpController.text = _otpController.text
                                    .substring(
                                        0, _otpController.text.length - 1);
                              });
                            },
                          )
                        ]),
                  ),
                ),
              ),
            );
          });
        },
      ),
    );
  }
}
