import 'dart:async';
import 'dart:developer';

import 'package:feelverapp/model/Login/login_model.dart';
import 'package:feelverapp/model/register/register_model.dart';


import 'package:feelverapp/service/Loading.dart';

import 'package:feelverapp/service/api.dart';
import 'package:feelverapp/service/base_presenter.dart';
import 'package:feelverapp/ui/home/home.dart';
import 'package:feelverapp/ui/login/login.dart';
import 'package:feelverapp/ui/register/register_email.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';



class RegisterPresenter extends BasePresenter<Registerpage> {
  Api _api;
 Timer _timer;
  final formKey = GlobalKey<FormState>();
  TextEditingController emailCtrl = TextEditingController();
  TextEditingController passCtrl = TextEditingController();
  TextEditingController firstnameCtrl = TextEditingController();
  TextEditingController lastnameCtrl = TextEditingController();
  TextEditingController phonenumberCtrl = TextEditingController();





  RegisterPresenter(State<Registerpage> state) : super(state);






/////email Login/////////

letCheckData() async {
  
     
       try {
        if (emailCtrl.text.isEmpty ) throw ('กรุณากรอก\nอีเมล์');
           else if (passCtrl.text.isEmpty ) throw('กรุณากรอก\nรหัสผ่าน');
           else if(firstnameCtrl.text.isEmpty) throw('กรุณากรอกชื่อ');
           else if(lastnameCtrl.text.isEmpty) throw('กรุณากรอกนามสกุล');

            Pattern pattern =
           r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+";
        RegExp regex = new RegExp(pattern);
          if (!regex.hasMatch(emailCtrl.text))
            throw  ('รูปแบบอีเมล์\nไม่ถูกต้อง');
            
            Pattern pattern2 =
           r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$';
        RegExp regex2 = new RegExp(pattern2);
       if (!regex2.hasMatch(passCtrl.text))
            throw  ('รหัสผ่านต้องมีความยาวอย่าง น้อย 8 ตัวอักษร และต้องประกอบด้วยอักขระ ดังต่อไปนี้\n- ตัวอักษรภาษาอังกฤษ ตัวพิมพ์เล็ก (a-z) \n- ตัวอักษรภาษาอังกฤษ ตัวพิมพ์ใหญ่ (A-Z) \n- ตัวเลข (0-9)');
       

else {
         await letregis();
        print("completeee");
        }
      } catch (e) {
          Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: '$e',
        content: Icon(Icons.warning,color: Colors.orange,size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () => Navigator.pop(state.context),
            child: Text(
              "ตกลง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
      }

  } 

  letregis() async {
 LoadingView(state.context).show();
    _api = Api<RegisterModel>();

    var res = await _api.register({
      "access_type":"mobile",
      "name":firstnameCtrl.text,
      "last_name":lastnameCtrl.text,
      "email": emailCtrl.text,
      'password':passCtrl.text
    });
 LoadingView(state.context).hide();


    if (res.fail == null) {
      Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: "สมัครสมาชิกสำเร็จ",
        content: Icon(Icons.check_circle,color: Color.fromRGBO(106, 179, 170, 1),size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () =>  
Navigator.pushReplacement(state.context, CupertinoPageRoute(builder: (_) => LoginPage())),
            child: Text(
              "ตกลง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
      RegisterModel model = res.success;
     // print("Username ="+"${model.user}");
     
      print("Regist message ="+"${model.message}");
          } else {
   Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: "อีเมล์\nมีการลงทะเบียนแล้ว",
        content: Icon(Icons.warning,color: Colors.orange,size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () => Navigator.pop(state.context),
            child: Text(
              "ลองอีกครั้ง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
    }
  }

















///////phone log in////////////////




  letregis_phone() async {
 LoadingView(state.context).show();
    _api = Api<RegisterModel>();

    var res = await _api.register({
      "access_type":"mobile",
      "phone_number": phonenumberCtrl.text,
      'password':passCtrl.text
    });
 LoadingView(state.context).hide();


    if (res.fail == null) {
      Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: "สมัครสมาชิกสำเร็จ",
        content: Icon(Icons.check_circle,color: Color.fromRGBO(106, 179, 170, 1),size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () =>  
Navigator.pushReplacement(state.context, CupertinoPageRoute(builder: (_) => LoginPage())),
            child: Text(
              "ตกลง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
      RegisterModel model = res.success;
     // print("Username ="+"${model.user}");
     
      print("Regist message  ="+"${model.message}");
          } else {
   Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: "เบอร์โทรศัพท์ของท่าน\nมีการลงทะเบียนแล้ว",
        content: Icon(Icons.warning,color: Colors.orange,size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () => Navigator.pop(state.context),
            child: Text(
              "ลองอีกครั้ง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
    }
  }
     letCheckData_phone() async {
      // if(!verifyPhoneState){
      //     throw(allTranslations.text(key: 'please_verify_phone'));
      //   }
     
       try {
        if (phonenumberCtrl.text.isEmpty ) throw ('กรุณากรอก\nเบอร์โทรศัพท์มือถือ');
           else if (passCtrl.text.isEmpty ) throw('กรุณากรอก\nรหัสผ่าน');
         


             Pattern pattern =
           r'(^(?:[+0]9)?[0-9]{10,12}$)';
        RegExp regex = new RegExp(pattern);
        if (!regex.hasMatch(phonenumberCtrl.text))
            throw  ('รูปแบบเบอร์โทรศัพท์\nไม่ถูกต้อง');

                  Pattern pattern2 =
           r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$';
        RegExp regex2 = new RegExp(pattern2);
       if (!regex2.hasMatch(passCtrl.text))
            throw  ('รหัสผ่านต้องมีความยาวอย่าง น้อย 8 ตัวอักษร และต้องประกอบด้วยอักขระ ดังต่อไปนี้\n- ตัวอักษรภาษาอังกฤษ ตัวพิมพ์เล็ก (a-z) \n- ตัวอักษรภาษาอังกฤษ ตัวพิมพ์ใหญ่ (A-Z) \n- ตัวเลข (0-9)');
       

else {
           await letregis_phone();
            print("complete");
        }
      } catch (e) {
          Alert(
        style: AlertStyle(
      animationType: AnimationType.fromTop,
      isCloseButton: false,
     
      ),
        context: state.context,
        title: '$e',
        content: Icon(Icons.warning,color: Colors.orange,size: 80,),
        buttons: [
          DialogButton(
            color:  Color.fromRGBO(106, 179, 170, 1),
            onPressed: () => Navigator.pop(state.context),
            child: Text(
              "ตกลง",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
      }

  } 


 
  


  // facebookLogin() async {
  //   try {
  //     await _facebookLogin.logIn(['email']).then((result) async {
  //       var fbData = await Api().getFacebookInfo(result.accessToken.token);
  //       print(fbData);

  //       await _letSocialSignIn(result.accessToken.userId, 'facebook')
  //           .then((value) {
  //         if (value) {
  //           Navigator.popUntil(state.context, (route) => route.isFirst);
  //           Navigator.pushReplacement(state.context, CupertinoPageRoute(builder: (_) => 
              
  //     NavigatorPage(),
  //           ));
  //         } else {
  //           Navigator.push(
  //               state.context,
  //               CupertinoPageRoute(
  //                   builder: (_) => SignUpEmail(
  //                         socialType: SocialType.facebook,
  //                         socialData: new RegisterSocialDataModel(
  //                           socialId: result.accessToken.userId,
  //                           token: result.accessToken.token,
  //                           email: fbData['email'],
  //                           firstName: fbData['first_name'],
  //                           lastName: fbData['last_name'],
  //                         ),
  //                       )));
  //         }
  //       });
  //     });
  //   } catch (e) {
  //     print(e);
  //   }
  // }

 
}
