import UIKit
import SafariServices
import Async
import WowonderMessengerSDK
import Toast_Swift

class SignUpVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet var bgView: UIView!
    @IBOutlet weak var usernameTextField: UITextField!
    @IBOutlet weak var firstNameTextField: UITextField!
    @IBOutlet weak var lastNameTextField: UITextField!
    @IBOutlet weak var passwordVisibleButton: UIButton!
    @IBOutlet weak var confirmPasswordTextFieldTF: UITextField!
    @IBOutlet weak var passwordTextFieldTF: UITextField!
    @IBOutlet weak var emailTextFieldTF: UITextField!
    @IBOutlet weak var agreeTermsBtn: UIButton!
    @IBOutlet weak var termOfServiceBtn: UIButton!
    @IBOutlet weak var signupBtn: UIButton!
    @IBOutlet weak var termsandConditionLabel: UILabel!
    @IBOutlet weak var genderTextFieldTF: UITextField!
    
    // MARK: - Properties
    
    var iconClick = true
    var gender = ""
    private var agreeStatus = false
    let socketHelper = SocketHelper.shared
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    // Password Toggle Button Action
    @IBAction func passwordToggleButtonAction(_ sender: UIButton) {
        if iconClick {
            passwordTextFieldTF.isSecureTextEntry = false
            sender.setImage(UIImage(named: "ic_Show_Password"), for: .normal)
        } else {
            passwordTextFieldTF.isSecureTextEntry = true
            sender.setImage(UIImage(named: "ic_hide_Password"), for: .normal)
        }
        iconClick = !iconClick
    }
    
    // Confirm Password Toggle Button Action
    @IBAction func confirmPasswordToggleButtonAction(_ sender: UIButton) {
        if iconClick {
            confirmPasswordTextFieldTF.isSecureTextEntry = false
            sender.setImage(UIImage(named: "ic_Show_Password"), for: .normal)
        } else {
            confirmPasswordTextFieldTF.isSecureTextEntry = true
            sender.setImage(UIImage(named: "ic_hide_Password"), for: .normal)
        }
        iconClick = !iconClick
    }
    
    // Gender Button Action
    @IBAction func genderButtonAction(_ sender: UIButton) {
        if let newVC = R.storyboard.popup.genderAlertVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // SignUp Button Action
    @IBAction func signUpButtonAction(_ sender: UIButton) {
        self.handleRegisterButtonTap()
    }
    
    // Agree Terms Button Action
    @IBAction func agreeTermsButtonAction(_ sender: UIButton) {
        self.agreeStatus = !self.agreeStatus
        if self.agreeStatus {
            self.agreeTermsBtn.setImage(UIImage(named: "ic_checkbox"), for: .normal)
        } else {
            self.agreeTermsBtn.setImage(UIImage(named: "ic_uncheckgey"), for: .normal)
        }
    }
    
    // TermsOfService Button Action
    @IBAction func termsOfServiceButtonAction(_ sender: UIButton) {
        if let url = URL(string: API.WEBSITE_URL.terms) {
            let safariViewController = SFSafariViewController(url: url)
            safariViewController.delegate = self
            present(safariViewController, animated: true, completion: nil)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.dismissKeyboard()
        self.setUpUI()
        self.termOfServiceBtn.setTitleColor(UIColor.accent, for: .normal)
        self.signupBtn.backgroundColor = UIColor.accent
        self.agreeTermsBtn.setTitleColor(UIColor.accent, for: .normal)
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.close(_:)))
        tap.cancelsTouchesInView = false
        self.bgView.addGestureRecognizer(tap)
    }
    
    @objc func close(_ sender: UITapGestureRecognizer? = nil) {
        self.usernameTextField.resignFirstResponder()
        self.firstNameTextField.resignFirstResponder()
        self.lastNameTextField.resignFirstResponder()
        self.emailTextFieldTF.resignFirstResponder()
        self.passwordTextFieldTF.resignFirstResponder()
        self.confirmPasswordTextFieldTF.resignFirstResponder()
    }
    
    // SetUp UI
    func setUpUI() {
        self.termOfServiceBtn.underline()
    }
    
    private func handleRegisterButtonTap() {
        if appDelegate.isInternetConnected {
            if !self.agreeStatus {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Warning !", comment: "Warning !")
                securityAlertVC?.errorText = NSLocalizedString("You can not access your disapproval of the Terms and Conditions.", comment: "You can not access your disapproval of the Terms and Conditions.")
                self.present(securityAlertVC!, animated: true, completion: nil)
            } else if self.usernameTextField.text?.isEmpty ?? false {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                securityAlertVC?.errorText = NSLocalizedString("Please enter username.", comment: "Please enter username.")
                self.present(securityAlertVC!, animated: true, completion: nil)
            } else if self.firstNameTextField.text?.isEmpty ?? false {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                securityAlertVC?.errorText = NSLocalizedString("Please enter first name.", comment: "Please enter first name.")
                self.present(securityAlertVC!, animated: true, completion: nil)
            } else if self.lastNameTextField.text?.isEmpty ?? false {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                securityAlertVC?.errorText = NSLocalizedString("Please enter last name.", comment: "Please enter last name.")
                self.present(securityAlertVC!, animated: true, completion: nil)
            } else if emailTextFieldTF.text?.isEmpty ?? false {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                securityAlertVC?.errorText = NSLocalizedString("Please enter email.", comment: "Please enter email.")
                self.present(securityAlertVC!, animated: true, completion: nil)
            } else if passwordTextFieldTF.text?.isEmpty ?? false {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                securityAlertVC?.errorText = NSLocalizedString("Please enter password.", comment: "Please enter password.")
                self.present(securityAlertVC!, animated: true, completion: nil)
            } else if confirmPasswordTextFieldTF.text?.isEmpty ?? false {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                securityAlertVC?.errorText = NSLocalizedString("Please enter confirm password.", comment: "Please enter confirm password.")
                self.present(securityAlertVC!, animated: true, completion: nil)
            } else if passwordTextFieldTF.text != confirmPasswordTextFieldTF.text {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                securityAlertVC?.errorText = NSLocalizedString("Password do not match.", comment: "Password do not match.")
                self.present(securityAlertVC!, animated: true, completion: nil)
            } else if !(emailTextFieldTF.text?.isEmail ?? false) {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                securityAlertVC?.errorText = NSLocalizedString("Email is badly formatted.", comment: "Email is badly formatted.")
                self.present(securityAlertVC!, animated: true, completion: nil)
            } else {
                let username = self.usernameTextField.text ?? ""
                let first_name = self.firstNameTextField.text ?? ""
                let last_name = self.lastNameTextField.text ?? ""
                let email = self.emailTextFieldTF.text ?? ""
                let password = self.passwordTextFieldTF.text ?? ""
                let confirmPassword = self.confirmPasswordTextFieldTF.text ?? ""
                let deviceId = UserDefaults.standard.getDeviceId(Key: Local.DEVICE_ID.DeviceId)
                let gender = self.gender
                Async.background {
                    UserManager.instance.RegisterUser(first_name: first_name, last_name: last_name, Email: email, UserName: username, DeviceId: deviceId, Password: password, ConfirmPassword: confirmPassword, gender: gender, completionBlock: { (success, sessionError, serverError, error) in
                        if success != nil {
                            Async.main {
                                self.dismissProgressDialog {
                                    if success?.access_token == nil {
                                        if let alertVC = R.storyboard.popup.warningAlertVC() {
                                            alertVC.modalPresentationStyle = .overFullScreen
                                            alertVC.modalTransitionStyle = .crossDissolve
                                            alertVC.titleText = NSLocalizedString("Security", comment: "Security")
                                            alertVC.messageText = success?.message ?? ""
                                            self.present(alertVC, animated: true, completion: nil)
                                            alertVC.cancelButton.isHidden = true
                                        }
                                    } else {
                                        let user_Session = success?.getStringAnyData() ?? ["":""]
                                        UserDefaults.standard.setUserSession(value: user_Session, ForKey: Local.USER_SESSION.User_Session)
                                        AppInstance.instance.fetchUserProfile { userData in
                                            var getSwitchAccountData = UserDefaults.standard.getSwitchAccountData(Key: "Switch_Account_Data")
                                            let data = try! JSONSerialization.data(withJSONObject: getSwitchAccountData, options: [])
                                            let switchAccountData = try! JSONDecoder().decode([UserData].self, from: data)
                                            if switchAccountData.contains(where: { $0.user_id == userData?.user_data?.user_id }) {
                                                print("Switch Account Data Already Added")
                                            } else {
                                                var user = userData?.user_data?.getStringAnyData() ?? [:]
                                                user["access_token"] = success?.access_token
                                                getSwitchAccountData.append(user)
                                                UserDefaults.standard.setSwitchAccountData(value: getSwitchAccountData, ForKey: "Switch_Account_Data")
                                                print("Switch Account Data Added")
                                            }
                                        }
                                        let vc = R.storyboard.main.introVC()
                                        self.navigationController?.pushViewController(vc!, animated: true)
                                        self.view.makeToast(NSLocalizedString("Login Successfull!!", comment: "Login Successfull!!"))
                                    }
                                }
                            }
                        } else if sessionError != nil {
                            Async.main {
                                self.dismissProgressDialog {
                                    print("session Error = \(sessionError?.errors?.error_text ?? "")")
                                    let securityAlertVC = R.storyboard.main.securityPopupVC()
                                    securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                    securityAlertVC?.errorText = sessionError?.errors?.error_text ?? ""
                                    self.present(securityAlertVC!, animated: true, completion: nil)
                                }
                            }
                        } else if serverError != nil {
                            Async.main {
                                self.dismissProgressDialog {
                                    print("serverError = \(serverError?.errors?.error_text ?? "")")
                                    let securityAlertVC = R.storyboard.main.securityPopupVC()
                                    securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                    securityAlertVC?.errorText = sessionError?.errors?.error_text ?? ""
                                    self.present(securityAlertVC!, animated: true, completion: nil)
                                }
                            }
                        } else {
                            Async.main {
                                self.dismissProgressDialog {
                                    print("error = \(error?.localizedDescription ?? "")")
                                    let securityAlertVC = R.storyboard.main.securityPopupVC()
                                    securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                    securityAlertVC?.errorText = error?.localizedDescription ?? ""
                                    self.present(securityAlertVC!, animated: true, completion: nil)
                                }
                            }
                        }
                    })
                }
            }
        } else {
            self.dismissProgressDialog {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Internet Error", comment: "Internet Error")
                securityAlertVC?.errorText = InterNetError
                self.present(securityAlertVC!, animated: true, completion: nil)
                print("internetError - \(InterNetError)")
            }
        }
    }
    
}

// MARK: SFSafariViewControllerDelegate Methods
extension SignUpVC: SFSafariViewControllerDelegate {
    
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
    
}

// MARK: GenderAlertVCDelegate
extension SignUpVC: GenderAlertVCDelegate {
    
    func handleGenderTap(gender: String) {
        self.genderTextFieldTF.text = gender
        self.gender = gender.lowercased()
    }
    
}
