import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:peasmartcare/blocs/resend_otp/resend_otp_bloc.dart';
import 'package:peasmartcare/blocs/verify_otp/verify_otp_bloc.dart';
import 'package:peasmartcare/components/body_layout.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/constraints/image_asset.dart';
import 'package:peasmartcare/models/otp_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/pages/select_electricity_location/select_electricity_location.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:timer_count_down/timer_controller.dart';
import 'package:timer_count_down/timer_count_down.dart';

class SendOTPPage extends StatefulWidget {
  final String phoneNumber;
  final OtpModel otpData;

  const SendOTPPage({Key key, this.phoneNumber, this.otpData})
      : super(key: key);

  @override
  _SendOTPPageState createState() => _SendOTPPageState();
}

class _SendOTPPageState extends State<SendOTPPage> {
  final CountdownController _countdown = CountdownController();
  final _formKey = GlobalKey<FormState>();
  bool _isSendOtp = false;
  bool _showCountdown = true;
  OtpModel _otpData;
  TextEditingController _otpNumber = TextEditingController();

  StreamController<ErrorAnimationType> errorController;
  String currentText = "";
  bool hasError = false;

  @override
  void dispose() {
    _otpNumber.dispose();

    super.dispose();
  }

  @override
  void initState() {
    _otpData = widget.otpData;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PEAAppBar(
        actions: <Widget>[],
      ),
      body: BodyLayout(
        layoutType: LayoutType.ONLY_CHILD,
        color: Colors.purple[200],
        top: 50,
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                _body(),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _body() {
    return Positioned(
      child: Padding(
        padding: const EdgeInsets.only(top: 0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              alignment: Alignment.topCenter,
              child: Image.asset(
                ImageAsset.peaHorizontalLogo,
                width: 300,
                fit: BoxFit.fill,
              ),
            ),
            SizedBox(
              height: 20,
            ),
            Text("OTP Code",
                style:
                    TextStyle(fontSize: 32, color: Color(AppData.yellowColor))),
            _form()
          ],
        ),
      ),
    );
  }

  Widget _form() {
    return Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          BlocListener<VerifyOtpBloc, VerifyOtpState>(
            listener: (context, state) {
              print("xxssss ${VerifyOtpLoaded}");
              if (state is VerifyOtpLoaded) {
                _otpNumber.text = "";
                if (state.result) {
                  SweetAlert.show(
                    context,
                    subtitle: "สำเร็จ",
                    style: SweetAlertStyle.success,
                    showCancelButton: false,
                    onPress: (bool isConfirm) {
                      Navigator.pop(context);
                      Navigator.pushReplacement(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                SelectElectricityLocationPage()),
                      );
                      return false;
                    },
                  );
                } else {
                  SweetAlert.show(
                    context,
                    subtitle: "OTP ไม่ถูกต้อง",
                    style: SweetAlertStyle.error,
                  );
                }
              } else if (state is VerifyOtpError) {
                SweetAlert.show(
                  context,
                  subtitle: state.message,
                  style: SweetAlertStyle.error,
                );
              } else if (state is VerifyOtpErrorUnauthorized) {
                Navigator.of(context).popUntil((route) => route.isFirst);
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(builder: (context) => LogoutPage()),
                );
              }
            },
            child: BlocBuilder<VerifyOtpBloc, VerifyOtpState>(
              builder: (context, state) {
                if (state is VerifyOtpLoading) {
                  return Loading();
                }
                return Container(
                  width: 350,
                  padding: const EdgeInsets.fromLTRB(25, 40, 25, 15),
                  child: PinCodeTextField(
                    length: 6,
                    obsecureText: false,
                    animationType: AnimationType.fade,
                    textCapitalization: TextCapitalization.characters,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly
                    ],
                    textInputType: TextInputType.number,
                    backgroundColor: Colors.transparent,
                    controller: _otpNumber,
                    textStyle: TextStyle(
                      color: Colors.grey[800],
                      fontSize: 30,
                      fontWeight: FontWeight.bold,
                    ),
                    validator: (v) {
                      // if (v.length < 4) {
                      //   return "Enter your passcode";
                      // } else {
                      //   return null;
                      // }
                    },
                    pinTheme: PinTheme(
                      shape: PinCodeFieldShape.underline,
                      fieldHeight: 50,
                      fieldWidth: 40,
                    ),
                    // textInputType: TextInputType.number,
                    autoDisposeControllers: false,
                    onCompleted: (val) {
                      context.read<VerifyOtpBloc>().add(
                            VerifyOtpOnSubmit(
                              otpId: _otpData.id,
                              otp: val,
                            ),
                          );
                    },
                    onChanged: (v) {
                      currentText = v;
                    },
                  ),
                );
              },
            ),
          ),
          Container(
            child: Text(
              "รหัสอ้างอิง : ${_otpData?.refCode ?? ""}",
              style: TextStyle(
                fontSize: 18,
                color: Color(AppData.yellowColor),
              ),
            ),
          ),
          Countdown(
            controller: _countdown,
            seconds: 60,
            build: (_, double time) {
              return _showCountdown
                  ? Text(
                      Duration(seconds: time.round())
                          .toString()
                          .substring(2, 7),
                      style: TextStyle(
                        fontSize: 18,
                        color: Color(AppData.yellowColor),
                      ),
                    )
                  : Text("");
            },
            interval: Duration(milliseconds: 100),
            onFinished: () {
              setState(() {
                _isSendOtp = true;
                _showCountdown = false;
              });
            },
          ),
          BlocListener<ResendOtpBloc, ResendOtpState>(
            listener: (context, state) {
              if (state is ResendOtpErrorUnauthorized) {
                Navigator.of(context).popUntil((route) => route.isFirst);
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(builder: (context) => LogoutPage()),
                );
              }
            },
            child: BlocListener<ResendOtpBloc, ResendOtpState>(
              listener: (context, state) {
                if (state is ResendOtpLoaded) {
                  if (state.result) {
                    _countdown.restart();
                    setState(() {
                      _isSendOtp = false;
                      _showCountdown = true;
                      _otpData = state.otpResult;
                    });
                  }
                }
              },
              child: BlocBuilder<ResendOtpBloc, ResendOtpState>(
                builder: (context, state) {
                  if (state is ResendOtpLoading) {
                    return Loading(height: 50);
                  }
                  return Container(
                    padding: EdgeInsets.fromLTRB(0, 30, 0, 15),
                    child: RaisedButton(
                      padding: EdgeInsets.only(
                          top: 12, left: 30, right: 30, bottom: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(7),
                      ),
                      child: Text(
                        "ส่งซ้ำ",
                        style: TextStyle(
                          fontWeight: FontWeight.w800,
                          color: Colors.white,
                          fontSize: 18,
                        ),
                      ),
                      color: _isSendOtp
                          ? Color(AppData.yellowColor)
                          : Colors.grey[300],
                      onPressed: () {
                        if (_isSendOtp && _formKey.currentState.validate()) {
                          FocusScope.of(context).requestFocus(FocusNode());

                          context
                              .read<ResendOtpBloc>()
                              .add(ResendOtpOnSubmit());
                        }
                      },
                    ),
                  );
                },
              ),
            ),
          ),
          _remark(),
        ],
      ),
    );
  }

  Widget _remark() {
    return Container(
      // width: 200,
      padding: EdgeInsets.all(15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            "หมายเหตุ* ",
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Colors.red[800],
              fontSize: 14,
              fontWeight: FontWeight.normal,
            ),
          ),
          Text(
            "ระบบได้ส่ง OTP ในการลงทะเบียนแล้วที่โทรศัพท์หมายเลข ${widget.phoneNumber} \nกรุณายืนยันรหัสภายใน 15 นาที หากไม่ได้รับ SMS ในเวลาที่กำหนดให้กด 'ส่งซ้ำ'",
            overflow: TextOverflow.clip,
            style: TextStyle(
              color: Color(AppData.whiteColor),
              fontWeight: FontWeight.w500,
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }
}
