import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:feelverapp/model/Login/login_model.dart';
import 'package:feelverapp/model/editprofile/getprofilemodel.dart';
import 'package:feelverapp/model/forgetpassword/forgetpassModel.dart';

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

import 'package:feelverapp/service/api.dart';
import 'package:feelverapp/service/base_presenter.dart';
import 'package:feelverapp/ui/ForgetPassword/forgetpassword.dart';
import 'package:feelverapp/ui/home/home.dart';
import 'package:feelverapp/ui/login/login.dart';
import 'package:feelverapp/util/Accout_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';

import 'edit_profile.dart';

class EditprofilePresenter extends BasePresenter<EditProfile> {
  Api _api;
  File imageFile;
  String uid = "16";
  final formKey = GlobalKey<FormState>();

  String age, lastname, firstname, sex, address, email, phone;
  GetprofileModel getmodel;
  TextEditingController addresCtrl = TextEditingController();
  TextEditingController ageCtrl = TextEditingController();
  TextEditingController selectedSex = TextEditingController();
  TextEditingController nameCtrl = TextEditingController();
  TextEditingController phoneCtrl = TextEditingController();
  TextEditingController emailCtrl = TextEditingController();
  TextEditingController lnameCtrl = TextEditingController();

  EditprofilePresenter(State<EditProfile> state) : super(state);

  letCheckData() async {
    try {
      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'(^(?:[+0]9)?[0-9]{10,12}$)';
      RegExp regex2 = new RegExp(pattern2);
      if (!regex2.hasMatch(phoneCtrl.text))
        throw ('รูปแบบเบอร์โทรศัพท์\nไม่ถูกต้อง');

      if (selectedSex.text != "ชาย") {
        if (selectedSex.text != "หญิง") throw ('กรุณาระบุเพศ\nชาย/หญิง');
        else {
        await letedit();
        print("completeee");
      }
      } else {
        await letedit();
        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();
    }
  }

  letedit() async {
    _api = Api<FogetPasswordModel>();
    LoadingView(state.context).show();
    var res = await _api.editProfile({
      'id': getmodel.result[0].id.toString(),
      'name': nameCtrl.text,
      'lastname': lnameCtrl.text,
      'phone': phoneCtrl.text,
      'email': emailCtrl.text,
      'sex': selectedSex.text == "ชาย" ? 'm' : 'w',
      'image': imageFile != null ? _getImageBase64() : " ",
    });

    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.pop(state.context),
              child: Text(
                "ยืนยัน",
                style: TextStyle(color: Colors.white, fontSize: 20),
              ),
            )
          ]).show();
    } else {
      Alert(
          style: AlertStyle(
            animationType: AnimationType.fromTop,
            isCloseButton: false,
          ),
          context: state.context,
          title: "ไม่สำเร็จ",
          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();
    }
  }

  _getImageBase64() {
    return base64.encode(imageFile.readAsBytesSync());
  }

  getprofile(String id) async {
    _api = Api<GetprofileModel>();

    var res = await _api.getprofile({
      "id": id
      
      
      });

    if (res.fail == null) {
      setState(() {
        getmodel = res.success;
        ageCtrl.text = getmodel.result[0].age.toString();
        nameCtrl.text = getmodel.result[0].name;
        lnameCtrl.text = getmodel.result[0].lastname;
        selectedSex.text = getmodel.result[0].sex == 'm' ? "ชาย" : "หญิง";
        addresCtrl.text = getmodel.result[0].address.toString();
        emailCtrl.text = getmodel.result[0].email;
        phoneCtrl.text = getmodel.result[0].phone.toString();
      });
    } 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();
    }
  }
}
