import 'dart:io' show Platform;
import 'package:device_info/device_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/api.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 Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

setLoading(bool boolean) {
  _LoginState.showSpinner = boolean;
}

TextEditingController username = TextEditingController();
TextEditingController password = TextEditingController();
TextEditingController phonenumber = TextEditingController();
FirebaseMessaging firebaseMessaging = FirebaseMessaging();

class _LoginState extends State<Login> with SingleTickerProviderStateMixin {
  static final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
  AnimationController _controller;
  Animation animation;
  FocusNode _focusNode = FocusNode();
  static String osName;
  static String osVersion;
  static String model = "";
  double _padding;
  double _heightHeader;
  double _heightImg;
  static bool showSpinner = false;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
        duration: Duration(milliseconds: 100), vsync: this, upperBound: 120);
    animation = CurvedAnimation(parent: _controller, curve: Curves.easeIn);
    _heightHeader = 600;
    _heightImg = 120;
    _padding = 70.0;

    _controller.forward();

    setState(() {
      getDeviceInfo();
      _heightImg = 120;
    });

    _controller.addListener(() {
      setState(() {
        _controller.addStatusListener((status) {
          if (status == AnimationStatus.completed) {
            setState(() {
              _heightHeader = 600;
              _heightImg = _controller.value;
              _padding = 150;
            });
          } else if (status == AnimationStatus.dismissed) {
            setState(() {
              _heightHeader = 400;
              _heightImg = 70;
              _padding = 110;
            });
          }
        });
      });
    });

    _focusNode.addListener(() {
      // เมื่อมีการคลิก นอก/ใน ช่องกรอกข้อความ
      if (_focusNode.hasFocus) {
        setState(() {
          _controller.reverse();
        });
      } else {
        setState(() {
          _heightHeader = _heightHeader;
          _heightImg = 120;
          _padding = 70;
          _controller.forward();
        });
      }
    });

    firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, badge: true, alert: true));
    firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registersed: $settings");
    });
  }

  loginVerify(context, Map json, phoneNumber) async {
    print(AppUrl.PEALogin);
    var response;
    try {
      response = await AppApi.post2(AppUrl.PEALogin, json).catchError((error) {
        print(error);
        throw error;
      }); // เรียกใช้ api

      print(response);
    } catch (e) {
      print(e);
    }

    if (response['Message'] == null) {
      print("Verify User Success");
      if (phoneNumber != "1987654321") {
        AppUrl.AuthenKey = response['authenKey'];
        await sendOTP(context);
      } else {
        await LoginModel.login(context, json);
      }
    } else {
      setState(() {
        showSpinner = false;
      });

      alertForm(context, "แจ้งเตือน", "ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง");
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  getDeviceInfo() async {
    if (Platform.isAndroid) {
      var androidInfo = await DeviceInfoPlugin().androidInfo;
      setState(() {
        osName = "Android";
        osVersion = androidInfo.version.release;
        model = androidInfo.model;
        print('$osName -> $osVersion <-  $model');
      });
    }
    if (Platform.isIOS) {
      var iosInfo = await DeviceInfoPlugin().iosInfo;
      setState(() {
        osName = iosInfo.systemName;
        osVersion = iosInfo.systemVersion;
        model = iosInfo.model;
        print('$osName -> $osVersion <-  $model');
        // iOS 13.1, iPhone 11 Pro Max iPhone
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (showSpinner == true) {
      AppLoader.show();
    }
    if (showSpinner == false) {
      AppLoader.hide();
    }
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: GestureDetector(
        onTap: () {
          _controller.forward();
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(top: mediaQuery(context, 'h', _padding)),
              width: mediaQuery(context, 'w', 1125),
              height: mediaQuery(context, 'h', _heightHeader),
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(
                    AppAssets.bg_login,
                  ),
                  fit: BoxFit.cover,
                ),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Flexible(
                    child: Column(
                      children: <Widget>[
                        Container(
                          height: _heightImg,
                          width: mediaQuery(context, 'w', 700.34),
                          child: Image.asset(AppAssets.PEA_logo),
                        ),
                        SizedBox(
                          height: 0,
                        ),
                        // Text(
                        //   'CRM MOBILE WORKFORCE',
                        //   style: TextStyle(
                        //     fontSize: 15,
                        //     color: AppColors.color,
                        //   ),
                        // ),
                      ],
                    ),
                  ),
                ],
              ), // เขหัวโลโก้
            ),
            SizedBox(
              height: mediaQuery(context, 'h', 20),
            ),
            Flexible(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text(
                    'ลงทะเบียน / เข้าสู่ระบบ',
                    style: TextStyle(
                      fontSize: 26,
                      color: AppColors.color_text,
                    ),
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 15),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 40, right: 40),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'ชื่อผู้ใช้งาน* :',
                          style: TextStyle(
                            fontSize: 14,
                            color: AppColors.color_text,
                          ),
                        ),
                        SizedBox(
                          height: mediaQuery(context, 'h', 15),
                        ),
                        TextField(
                          controller: username,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.black,
                          ),
                          keyboardType: TextInputType.number,
                          decoration: InputDecoration(
                            contentPadding: EdgeInsets.fromLTRB(
                              mediaQuery(context, 'w', 50),
                              mediaQuery(context, 'h', 50),
                              mediaQuery(context, 'w', 50),
                              mediaQuery(context, 'h', 50),
                            ),
                            filled: true,
                            fillColor: Colors.white,
                            hintText: "ชื่อผู้ใช้งาน",
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(23.0),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(23.0),
                            ),
                          ),
                          onTap: () {
                            setState(() {
                              _controller.reverse();
                            });
                          },
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Text(
                          'รหัสผ่าน* :',
                          style: TextStyle(
                            fontSize: 14,
                            color: AppColors.color_text,
                          ),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        TextField(
                          controller: password,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.black,
                          ),
                          obscureText: true,
                          decoration: InputDecoration(
                            contentPadding: EdgeInsets.fromLTRB(
                              mediaQuery(context, 'w', 50),
                              mediaQuery(context, 'h', 50),
                              mediaQuery(context, 'w', 50),
                              mediaQuery(context, 'h', 50),
                            ),
                            filled: true,
                            fillColor: Colors.white,
                            hintText: "รหัสผ่าน",
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(23.0),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(23.0),
                            ),
                          ),
                          onTap: () {
                            setState(() {
                              _controller.reverse();
                            });
                          },
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Text(
                          'หมายเลขโทรศัพท์มือถือ* :',
                          style: TextStyle(
                            fontSize: 14,
                            color: AppColors.color_text,
                          ),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Container(
                          width: mediaQuery(context, 'w', 1100),
                          child: TextField(
                            controller: phonenumber,
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.black,
                            ),
                            keyboardType: TextInputType.number,
                            decoration: InputDecoration(
                              contentPadding: EdgeInsets.fromLTRB(
                                mediaQuery(context, 'w', 50),
                                mediaQuery(context, 'h', 50),
                                mediaQuery(context, 'w', 50),
                                mediaQuery(context, 'h', 50),
                              ),
                              filled: true,
                              fillColor: Colors.white,
                              hintText: "หมายเลขโทรศัพท์มือถือ",
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(23.0),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(23.0),
                              ),
                            ),
                            onTap: () {
                              setState(() {
                                _controller.reverse();
                              });
                            },
                          ),
                        ),
                        SizedBox(
                          height: 30,
                        ),
                        SizedBox(
                          width: mediaQuery(context, 'w', 1100),
                          child: RaisedButton(
                            onPressed: () async {
                              // setState(() {
                              //   showSpinner = true;
                              //   print("ontab");
                              //
                              // });
                              await verifyPwd(context);
                            },
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(25),
                            ),
                            color: AppColors.PURPLE,
                            padding: const EdgeInsets.only(
                                top: 8, bottom: 8, left: 60),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                Text(
                                  'ลงทะเบียน / เข้าสู่ระบบ',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 17,
                                  ),
                                ),
                                SizedBox(
                                  width: mediaQuery(context, 'w', 50),
                                ),
                                Container(
                                  width: mediaQuery(context, 'w', 100),
                                  height: mediaQuery(context, 'w', 100),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(17),
                                    color: Colors.white,
                                  ),
                                  child: Icon(
                                    Icons.arrow_forward_ios,
                                    color: AppColors.PURPLE,
                                    size: mediaQuery(context, 'h', 60),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  verifyPwd(context) async {
    print(username.text);

    FirebaseMessaging firebaseMessaging = FirebaseMessaging();
    print("firebaseMessaging : ${firebaseMessaging}");

    firebaseMessaging.getToken().then((String token) async {
      assert(token != null);
      print("Token : $token");

      AppUrl.os = osName;
      AppUrl.osVersion = osVersion;
      AppUrl.model = model;

      Map<String, dynamic> dataLogin = {
        "UserName": username.text,
        "Password": password.text,
        "Token": token,
        "OS": osName,
        "Version": osVersion,
        "Model": model,
      };
      print("------- verifyPwd ----------");
      print(dataLogin);
      final response = await loginVerify(context, dataLogin, phonenumber.text);
      return response;
    });
  }

  sendOTP(context) async {
    if (await checkForm([
      username.text,
      password.text,
      phonenumber.text,
    ])) {
      Map<String, dynamic> data = {
        "Mobile": phonenumber.text,
        "OTPMessage": "**pw**",
        "AuthenKey": AppUrl.AuthenKey.trim()
      };
      print("------- Set9/sendOTP ----------");
      print("OTP :: " + data.toString());

      LoginModel.sendOTP(
          context, data, phonenumber.text, username.text, password.text);
    } else {
      setState(() {
        showSpinner = false;
      });
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }
} //class
