//
//  SettingsVC.swift
//  WoWonder
//
//  Created by iMac on 05/09/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import UIKit
import Async
import WowonderMessengerSDK
import Toast_Swift

class MyAccountVC: BaseVC {
    
    // MARK: - IBIOutlets
    
    @IBOutlet weak var userNameTextField: UITextField!
    @IBOutlet weak var userNameTextFieldView: UIView!
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var emailTextFieldView: UIView!
    @IBOutlet weak var birthdayTextField: UITextField!
    @IBOutlet weak var genderTextField: UITextField!
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // Save Button Action
    @IBAction func saveButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.updateMyAccount()
    }
    
    // Birthday Button Action
    @IBAction func birthDayButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.setDatePickerView()
    }
    
    // Gender Button Action
    @IBAction func genderButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.genderAlertVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.textFieldSetUp()
        self.setData()
    }
    
    func textFieldSetUp() {
        self.userNameTextField.attributedPlaceholder = NSAttributedString(
            string: "Username",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.userNameTextField.delegate = self
        self.emailTextField.attributedPlaceholder = NSAttributedString(
            string: "Email",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.emailTextField.delegate = self
        self.birthdayTextField.attributedPlaceholder = NSAttributedString(
            string: "Birthday",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.genderTextField.attributedPlaceholder = NSAttributedString(
            string: "Gender",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
    }
    
    // Set Date Picker View
    func setDatePickerView() {
        let datePickerView = DatePickerView.init(frame: self.view.bounds)
        datePickerView.delegate = self
        self.view.addSubview(datePickerView)
        self.view.bringSubviewToFront(datePickerView)
    }
    
    private func setData() {
        self.userNameTextField.text = AppInstance.instance.userProfile?.username ?? ""
        self.emailTextField.text = AppInstance.instance.userProfile?.email ?? ""
        self.birthdayTextField.text = AppInstance.instance.userProfile?.birthday ?? ""
        self.genderTextField.text = AppInstance.instance.userProfile?.gender_text ?? ""
        self.birthdayTextField.text = AppInstance.instance.userProfile?.birthday ?? ""
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension MyAccountVC {
    
    private func updateMyAccount() {
        if Connectivity.isConnectedToNetwork() {
            let sessionToken = AppInstance.instance.sessionId ?? ""
            let userName = self.userNameTextField.text ?? ""
            let email = self.emailTextField.text ?? ""
            let birthday = self.birthdayTextField.text ?? ""
            let gender = (self.genderTextField.text ?? "").lowercased()
            Async.background {
                SettingsManager.instance.updateMyAccount(session_Token: sessionToken, username: userName, email: email, birthday: birthday, gender: gender, completionBlock: { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("success = \(success?.message ?? "")")
                                self.view.makeToast(success?.message ?? "")
                                AppInstance.instance.fetchUserProfile()
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                                self.view.makeToast(sessionError?.errors?.error_text ?? "")
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("serverError = \(serverError?.errors?.error_text ?? "")")
                                self.view.makeToast(serverError?.errors?.error_text ?? "")
                            }
                        }
                    } else {
                        Async.main {
                            self.dismissProgressDialog {
                                print("error = \(error?.localizedDescription ?? "")")
                                self.view.makeToast(error?.localizedDescription ?? "")
                            }
                        }
                    }
                })
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
}

// MARK: UITextFieldDelegate Methods
extension MyAccountVC: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case userNameTextField:
            self.userNameTextFieldView.borderColorV = .accent
        case emailTextField:
            self.emailTextFieldView.borderColorV = .accent
        default:
            break
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        switch textField {
        case userNameTextField:
            self.userNameTextFieldView.borderColorV = .color_divider
        case emailTextField:
            self.emailTextFieldView.borderColorV = .color_divider
        default:
            break
        }
    }
    
}

// MARK: DatePickerViewDelegate Methods
extension MyAccountVC: DatePickerViewDelegate {
    
    func datePickerOkButtonAction(view: DatePickerView, sender: UIButton, date: Date) {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        self.birthdayTextField.text = formatter.string(from: date)
        view.removeFromSuperview()
    }
    
    func datePickerCancelButtonAction(view: DatePickerView, sender: UIButton) {
        view.removeFromSuperview()
    }
    
}

// MARK: GenderAlertVCDelegate Methods
extension MyAccountVC: GenderAlertVCDelegate {
    
    func handleGenderTap(gender: String) {
        self.genderTextField.text = gender
    }
    
}
