import 'dart:async';
import 'package:countdown_flutter/countdown_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/assets.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/model/login.dart';

class Otp extends StatefulWidget {
  final phonenumber;
  final username;
  final password;

  Otp(
    this.phonenumber,
    this.username,
    this.password,
  );

  @override
  _OtpState createState() => _OtpState(
        this.phonenumber,
        this.username,
        this.password,
      );
}

setLoadingOPT() {
  _OtpState.setStatus();
}

class _OtpState extends State<Otp> with SingleTickerProviderStateMixin {
  String phonenumber;
  String username;
  String password;
  String empID;

  _OtpState(this.phonenumber, this.username, this.password);

  // Variables
  Size _screenSize;
  int _currentDigit;
  int _firstDigit;
  int _secondDigit;
  int _thirdDigit;
  int _fourthDigit;
  int _fivethDigit;
  int _sixthDigit;
  static bool isLoading = false;
  int clear;

  String otpCode;

  String userName = "";
  bool didReadNotifications = false;
  int unReadNotificationsCount = 0;
  bool isVisibleKeyboard = false;
  bool showSendAgain = false;

  void onReady() {
    // Implement your code inside here
    setState(() {
      isVisibleKeyboard = false;
    });
    print('Screen is ready!');
  }

  static setStatus() {
    isLoading = false;
  }

  // Return "OTP" input field
  get _getInputField {
    return Container(
      alignment: Alignment.topCenter,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          _otpTextField(_firstDigit),
          _otpTextField(_secondDigit),
          _otpTextField(_thirdDigit),
          _otpTextField(_fourthDigit),
          _otpTextField(_fivethDigit),
          _otpTextField(_sixthDigit),
        ],
      ),
    );
  }

  // Returns "OTP" input part
  get _getInputPart {
    return Column(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        GestureDetector(
          onTap: (){
            setState(() {
              isVisibleKeyboard = false;
            });
          },
          child: Container(
            width: mediaQuery(context, 'w', 1125),
            height: mediaQuery(context, 'h', 780),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(
                  AppAssets.bg_login,
                ),
                fit: BoxFit.cover,
              ),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  AppAssets.PEA_logo,
                  width: mediaQuery(context, 'w', 700.34),
                  height: mediaQuery(context, 'h', 600.67),
                ),
                SizedBox(
                  height: mediaQuery(context, 'h', 30),
                ),
                // Text(
                //   'CRM MOBILE WORKFORCE',
                //   style: TextStyle(
                //     fontSize: mediaQuery(context, 'h', 43),
                //     color: AppColors.color,
                //   ),
                // ),
              ],
            ),
          ),
        ),
        GestureDetector(
          child: Column(
            children: [
              Container(
                alignment: Alignment.topCenter,
                child: Text(
                  'กรุณาระบุรหัส OTP',
                  style: TextStyle(
                    color: AppColors.color_text,
                    fontSize: mediaQuery(context, 'h', 80),
                  ),
                ),
              ),
              _getInputField,
            ],
          ),
          onTap: () {
            setState(() {
              isVisibleKeyboard = true;
            });
          },
        ),
        SizedBox(
          height: mediaQuery(context, 'h', 40),
        ),
        Container(
          width: mediaQuery(context, 'w', 800),
          height: mediaQuery(context, 'h', 150),
          child: RaisedButton(
            padding: EdgeInsets.only(left: 0),
            color: AppColors.color,
            onPressed: () async {
              setState(() {
                isLoading = true;
              });
              await verifyOTP(context);
            },
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(
                mediaQuery(context, 'h', 90),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  alignment: Alignment.center,
                  child: Text(
                    'ยืนยัน OTP',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: mediaQuery(context, 'h', 50),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        SizedBox(height: mediaQuery(context, 'h', 25)),
        showSendAgain
            ? Container(
                margin: EdgeInsets.only(
                  left: mediaQuery(context, "w", 100),
                  right: mediaQuery(context, "w", 100),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      "รหัสอ้างอิง : " + AppUrl.refCode,
                      style: TextStyle(
                        fontSize: mediaQuery(context, "h", 45),
                        color: AppColors.color,
                      ),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        SizedBox(
                          height: mediaQuery(context, "h", 130),
                          child: RaisedButton(
                            onPressed: () => {sendCodeToPhoneNumberAgain()},
                            color: AppColors.PURPLE,
                            child: Text(
                              'ส่ง OTP อีกครั้ง',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: mediaQuery(context, "h", 40)),
                            ),
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              )
            : Container(
                margin: EdgeInsets.only(
                  left: mediaQuery(context, "w", 70),
                  right: mediaQuery(context, "w", 70),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      "รหัสอ้างอิง : " + AppUrl.refCode,
                      style: TextStyle(
                        fontSize: mediaQuery(context, "h", 45),
                        color: AppColors.color,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    CountdownFormatted(
                      duration: Duration(seconds: 60),
                      onFinish: () {
                        setState(() {
                          showSendAgain = true;
                        });
                      },
                      builder: (BuildContext ctx, var remaining) {
                        return Text(
                          'ขอ OTP อีกครั้งใน ' + remaining,
                          style: TextStyle(
                            fontSize: mediaQuery(context, "h", 45),
                            color: AppColors.color,
                            fontWeight: FontWeight.bold,
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ),
        isVisibleKeyboard
            ? _getOtpKeyboard
            : Container(
                margin: EdgeInsets.all(10.0),
                child: Wrap(children: <Widget>[
                  Text(
                    'หมายเหตุ*',
                    style: TextStyle(
                      color: Colors.red,
                      fontSize: 15,
                    ),
                  ),
                  Text("ระบบได้ส่ง OTP ในการลงทะเบียนแล้วที่โทรศัพท์หมายเลข " +
                      phonenumber),
                  Text("กรุณายืนยันรหัสภายใน 1 นาที"),
                  Text("หากไม่ได้รับ SMS ในเวลาที่กำหนดให้กด 'ส่งซ้ำ'"),
                ]),
              ),
      ],
    );
  }

  // Returns "Otp" keyboard
  get _getOtpKeyboard {
    return Container(
        padding: EdgeInsets.all(1),
        height: (_screenSize.height / 2.22) - 20,
        child: Column(
          children: <Widget>[
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  _otpKeyboardInputButton(
                      label: "1",
                      onPressed: () {
                        _setCurrentDigit(1);
                      }),
                  _otpKeyboardInputButton(
                      label: "2",
                      onPressed: () {
                        _setCurrentDigit(2);
                      }),
                  _otpKeyboardInputButton(
                      label: "3",
                      onPressed: () {
                        _setCurrentDigit(3);
                      }),
                ],
              ),
            ),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  _otpKeyboardInputButton(
                      label: "4",
                      onPressed: () {
                        _setCurrentDigit(4);
                      }),
                  _otpKeyboardInputButton(
                      label: "5",
                      onPressed: () {
                        _setCurrentDigit(5);
                      }),
                  _otpKeyboardInputButton(
                      label: "6",
                      onPressed: () {
                        _setCurrentDigit(6);
                      }),
                ],
              ),
            ),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  _otpKeyboardInputButton(
                      label: "7",
                      onPressed: () {
                        _setCurrentDigit(7);
                      }),
                  _otpKeyboardInputButton(
                      label: "8",
                      onPressed: () {
                        _setCurrentDigit(8);
                      }),
                  _otpKeyboardInputButton(
                      label: "9",
                      onPressed: () {
                        _setCurrentDigit(9);
                      }),
                ],
              ),
            ),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  _otpKeyboardActionButton(
                      label: Icon(
                        Icons.arrow_drop_down,
                        color: Colors.black,
                        size: 60.0,
                      ),
                      onPressed: () {
                        setState(() {
                          isVisibleKeyboard = false;
                        });
                      }),
                  _otpKeyboardInputButton(
                      label: "0",
                      onPressed: () {
                        _setCurrentDigit(0);
                      }),
                  _otpKeyboardActionButton(
                      label: Icon(
                        Icons.backspace,
                        color: Colors.black,
                      ),
                      onPressed: () {
                        setState(() {
                          if (_sixthDigit != null) {
                            _sixthDigit = null;
                          } else if (_fivethDigit != null) {
                            _fivethDigit = null;
                          } else if (_fourthDigit != null) {
                            _fourthDigit = null;
                          } else if (_thirdDigit != null) {
                            _thirdDigit = null;
                          } else if (_secondDigit != null) {
                            _secondDigit = null;
                          } else if (_firstDigit != null) {
                            _firstDigit = null;
                          }
                        });
                      }),
                ],
              ),
            ),
          ],
        ));
  }

  // Overridden methods
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    _screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        color: Color(0xFFf2f5f7),
        width: _screenSize.width,
        child: _getInputPart,
      ),
    );
  }

  // Returns "Otp custom text field"
  Widget _otpTextField(int digit) {
    return Container(
      width: 35.0,
      height: 45.0,
      alignment: Alignment.center,
      child: Text(
        digit != null ? digit.toString() : "",
        style: TextStyle(
          fontSize: 30.0,
          color: AppColors.color,
        ),
      ),
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(
        width: 2.0,
        color: Colors.black,
      ))),
    );
  }

  // Returns "Otp keyboard input Button"
  Widget _otpKeyboardInputButton({String label, VoidCallback onPressed}) {
    return Container(
      width: mediaQuery(context, 'h', 200),
      height: mediaQuery(context, 'h', 200),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(
          mediaQuery(context, 'h', 110),
        ),
        color: Colors.white,
      ),
      child: InkWell(
        onTap: onPressed,
        child: Center(
          child: Text(
            label,
            style: TextStyle(
              fontSize: mediaQuery(context, 'h', 140),
              color: Colors.black,
            ),
          ),
        ),
      ),
    );
  }

  // Returns "Otp keyboard action Button"
  _otpKeyboardActionButton({Widget label, VoidCallback onPressed}) {
    return InkWell(
      onTap: onPressed,
      borderRadius: BorderRadius.circular(40.0),
      child: Container(
        height: 80.0,
        width: 80.0,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
        ),
        child: Center(
          child: label,
        ),
      ),
    );
  }

  // Current digit
  void _setCurrentDigit(int i) {
    setState(() {
      _currentDigit = i;
      if (_firstDigit == null) {
        _firstDigit = _currentDigit;
      } else if (_secondDigit == null) {
        _secondDigit = _currentDigit;
      } else if (_thirdDigit == null) {
        _thirdDigit = _currentDigit;
      } else if (_fourthDigit == null) {
        _fourthDigit = _currentDigit;
      } else if (_fivethDigit == null) {
        _fivethDigit = _currentDigit;
      } else if (_sixthDigit == null) {
        _sixthDigit = _currentDigit;
        var otp = _firstDigit.toString() +
            _secondDigit.toString() +
            _thirdDigit.toString() +
            _fourthDigit.toString() +
            _fivethDigit.toString() +
            _sixthDigit.toString();

        setState(() {
          otpCode = otp;
        });

        print(otpCode);
        // Verify your otp by here. API call
      }
    });
  }

  void clearOtp() {
    _fourthDigit = null;
    _thirdDigit = null;
    _secondDigit = null;
    _firstDigit = null;
    setState(() {});
  }

  sendCodeToPhoneNumberAgain() async {
    setState(() {
      otpCode = "";
      _firstDigit = clear;
      _secondDigit = clear;
      _thirdDigit = clear;
      _fourthDigit = clear;
      _fivethDigit = clear;
      _sixthDigit = clear;
    });

    Map<String, dynamic> data = {
      "Mobile": phonenumber,
      "OTPMessage": "**pw**",
      "AuthenKey": AppUrl.AuthenKey.trim()
    };

    var sendAgain = await LoginModel.sendOTPAgain(
        context, data, phonenumber, username, password);

    if (sendAgain) {
      setState(() {
        showSendAgain = false;
      });
    }
  }

  verifyOTP(context) async {
    if (await checkForm([
      otpCode,
    ])) {
      Map<String, dynamic> data = {
        "OTPid": AppUrl.otpId,
        "OTP": otpCode,
        "AuthenKey": AppUrl.AuthenKey.trim()
      };
      print("------- verifyOTP ----------");
      print(data);
      var response = await LoginModel.verifyOTP(context, data, username, password);
      await Future.delayed(const Duration(milliseconds: 2000));
      if(response == false){
        setState(() {
          isLoading = false;
        });
        alertForm(context, "แจ้งเตือน", "รหัส OTP ไม่ถูกต้อง");
        return;
      }
      isLoading = false;
      return;
    } else {
      setState(() {
        isLoading = false;
      });
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }
}