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

import UIKit
import Async
import WowonderMessengerSDK
import SDWebImage
import Toast_Swift

class EditProfileVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var userImageView: UIImageView!
    @IBOutlet weak var firstNameTextField: UITextField!
    @IBOutlet weak var firstNameTextFieldView: UIView!
    @IBOutlet weak var lastNameTextField: UITextField!
    @IBOutlet weak var lastNameTextFieldView: UIView!
    @IBOutlet weak var aboutTextView: UITextView!
    @IBOutlet weak var aboutView: UIView!
    @IBOutlet weak var facebookTextField: UITextField!
    @IBOutlet weak var twitterTextField: UITextField!
    @IBOutlet weak var instagramTextField: UITextField!
    @IBOutlet weak var vkTextField: UITextField!
    @IBOutlet weak var youtubeTextField: UITextField!
    @IBOutlet weak var workTextField: UITextField!
    @IBOutlet weak var studyTextField: UITextField!
    @IBOutlet weak var countryTextField: UITextField!
    @IBOutlet weak var mobileTextField: UITextField!
    @IBOutlet weak var websiteTextField: UITextField!
    @IBOutlet weak var relationshipTextField: UITextField!
    
    // MARK: - Properties
    
    var relationship_id = ""
    var country_id = ""
    private var imagePicker = UIImagePickerController()
    private var imageData: Data? = nil
    let countryData = CountryData.instance
    let socketHelper = SocketHelper.shared
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // Camera Button Action
    @IBAction func cameraButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.imageAlertVC() {
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            newVC.delegate = self
            self.present(newVC, animated: true)
        }
    }
    
    // Country Button Action
    @IBAction func countryButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.locationAlertVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Relationship Button Action
    @IBAction func relationshipButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.relationshipAlertVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Save Button Action
    @IBAction func saveButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.updateUserProfile()
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.textFieldSetUp()
        self.textViewSetup()
        self.setUserData()
    }
    
    func textFieldSetUp() {
        self.firstNameTextField.attributedPlaceholder = NSAttributedString(
            string: "First Name",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.firstNameTextField.delegate = self
        self.lastNameTextField.attributedPlaceholder = NSAttributedString(
            string: "Last Name",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.lastNameTextField.delegate = self
        self.facebookTextField.attributedPlaceholder = NSAttributedString(
            string: "Facebook",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.twitterTextField.attributedPlaceholder = NSAttributedString(
            string: "Twitter",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.instagramTextField.attributedPlaceholder = NSAttributedString(
            string: "Instagram",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.vkTextField.attributedPlaceholder = NSAttributedString(
            string: "VK",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.youtubeTextField.attributedPlaceholder = NSAttributedString(
            string: "Youtube",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.workTextField.attributedPlaceholder = NSAttributedString(
            string: "Work",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.studyTextField.attributedPlaceholder = NSAttributedString(
            string: "Study",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.countryTextField.attributedPlaceholder = NSAttributedString(
            string: "Country",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.mobileTextField.attributedPlaceholder = NSAttributedString(
            string: "Mobile",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.websiteTextField.attributedPlaceholder = NSAttributedString(
            string: "Website",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.relationshipTextField.attributedPlaceholder = NSAttributedString(
            string: "Relationship",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
    }
    
    func textViewSetup() {
        self.aboutTextView.addPlaceholder("About", with: UIColor.text_color_in_between)
        self.aboutTextView.delegate = self
    }
    
    func setUserData() {
        let imageUrl = URL(string: AppInstance.instance.userProfile?.avatar ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        self.userImageView.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            self.userImageView.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: ""))
        }
        self.firstNameTextField.text = AppInstance.instance.userProfile?.first_name
        self.lastNameTextField.text = AppInstance.instance.userProfile?.last_name
        self.aboutTextView.text = AppInstance.instance.userProfile?.about
        self.facebookTextField.text = AppInstance.instance.userProfile?.facebook
        self.twitterTextField.text = AppInstance.instance.userProfile?.twitter
        self.instagramTextField.text = AppInstance.instance.userProfile?.instagram
        self.vkTextField.text = AppInstance.instance.userProfile?.vk
        self.youtubeTextField.text = AppInstance.instance.userProfile?.youtube
        self.workTextField.text = AppInstance.instance.userProfile?.working
        self.studyTextField.text = AppInstance.instance.userProfile?.school
        self.country_id = AppInstance.instance.userProfile?.country_id ?? ""
        self.countryTextField.text = self.countryData.getCountryName(forID: self.country_id)
        self.mobileTextField.text = AppInstance.instance.userProfile?.phone_number
        self.websiteTextField.text = AppInstance.instance.userProfile?.website
        
        switch AppInstance.instance.userProfile?.relationship_id {
        case "0":
            self.relationshipTextField.text = "None"
            self.relationship_id = "0"
        case "1":
            self.relationshipTextField.text = "Single"
            self.relationship_id = "1"
        case "2":
            self.relationshipTextField.text = "In a reationship"
            self.relationship_id = "2"
        case "3":
            self.relationshipTextField.text = "Married"
            self.relationship_id = "3"
        case "4":
            self.relationshipTextField.text = "Engaged"
            self.relationship_id = "4"
        default:
            break
        }
    }
    
}

// MARK: UITextFieldDelegate Methods
extension EditProfileVC: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case firstNameTextField:
            self.firstNameTextFieldView.borderColorV = .accent
        case lastNameTextField:
            self.lastNameTextFieldView.borderColorV = .accent
        default:
            break
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        switch textField {
        case firstNameTextField:
            self.firstNameTextFieldView.borderColorV = .color_divider
        case lastNameTextField:
            self.lastNameTextFieldView.borderColorV = .color_divider
        default:
            break
        }
    }
    
}

// MARK: UITextViewDelegate Methods
extension EditProfileVC: UITextViewDelegate {
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        switch textView {
        case aboutTextView:
            self.aboutView.borderColorV = .accent
        default:
            break
        }
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        switch textView {
        case aboutTextView:
            self.aboutView.borderColorV = .color_divider
        default:
            break
        }
    }
    
}

// MARK: ImageAlertVCDelegate Methods
extension EditProfileVC: ImageAlertVCDelegate {
    
    func handleImageFromGalleryTap(_ sender: UIButton) {
        self.setupImagePicker(imagePickerSourceType: .PHOTO_LIBRARY)
    }
    
    func handleTakePictureFromCameraTap(_ sender: UIButton) {
        self.setupImagePicker(imagePickerSourceType: .CAMERA)
    }
    
    func setupImagePicker(imagePickerSourceType: ImagePickerSourceType) {
        self.view.endEditing(true)
        self.imagePicker.delegate = self
        switch imagePickerSourceType {
        case .CAMERA:
            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.imagePicker.sourceType = .camera
            } else {
                if let messageAlertVC = R.storyboard.popup.messageAlertVC() {
                    messageAlertVC.messageText = "You don't have camera"
                    self.present(messageAlertVC, animated: true, completion: nil)
                    messageAlertVC.confirmButton.isHidden = true
                    return
                }
            }
        case .PHOTO_LIBRARY:
            self.imagePicker.sourceType = .photoLibrary
        }
        self.imagePicker.mediaTypes = ["public.image"]
        self.imagePicker.allowsEditing = false
        self.present(self.imagePicker, animated: true, completion: nil)
    }
    
}

// MARK: UIImagePickerControllerDelegate Methods
extension EditProfileVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true) {
            if let image = info[.originalImage] as? UIImage {
                self.userImageView.image = image
                self.imageData = image.jpegData(compressionQuality: 1)
            }
        }
    }
    
}

// MARK: LocationAlertVCDelegate Methods
extension EditProfileVC: LocationAlertVCDelegate {
    
    func handleCountrySelection(country: CountryModel) {
        self.country_id = country.id
        self.countryTextField.text = country.name
    }
    
}

// MARK: Api Call
extension EditProfileVC {
    
    private func updateUserProfile() {
        if Connectivity.isConnectedToNetwork() {
            let session_Token = AppInstance.instance.sessionId ?? ""
            let first_name = self.firstNameTextField.text ?? ""
            let last_name = self.lastNameTextField.text ?? ""
            let about = self.aboutTextView.text ?? ""
            let facebook = self.facebookTextField.text ?? ""
            let twitter = self.twitterTextField.text ?? ""
            let instagram = self.instagramTextField.text ?? ""
            let vk = self.vkTextField.text ?? ""
            let youtube = self.youtubeTextField.text ?? ""
            let working = self.workTextField.text ?? ""
            let school = self.studyTextField.text ?? ""
            let phone_number = self.mobileTextField.text ?? ""
            let website = self.websiteTextField.text ?? ""
            Async.background {
                if self.imageData == nil {
                    SettingsManager.instance.updateUserProfile(session_Token: session_Token, first_name: first_name, last_name: last_name, about: about, facebook: facebook, twitter: twitter, instagram: instagram, vk: vk, youtube: youtube, working: working, school: school, country_id: self.country_id, phone_number: phone_number, website: website, relationship_id: self.relationship_id) { (success, sessionError, serverError, error) in
                        if success != nil {
                            Async.main {
                                self.dismissProgressDialog {
                                    print("success = \(success?.message ?? "")")
                                    self.view.makeToast(success?.message ?? "")
                                    self.socketHelper.emit(event: "on_name_changed", data: ["from_id": AppInstance.instance.sessionId ?? ""])
                                    AppInstance.instance.fetchUserProfile()
                                    self.navigationController?.popViewController(animated: true)
                                }
                            }
                        } 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 {
                    SettingsManager.instance.updateUserDataWithImage(session_Token: session_Token, avatar_data: self.imageData, first_name: first_name, last_name: last_name, about: about, facebook: facebook, twitter: twitter, instagram: instagram, vk: vk, youtube: youtube, working: working, school: school, country_id: self.country_id, phone_number: phone_number, website: website, relationship_id: self.relationship_id) { (success, sessionError, serverError, error) in
                        if success != nil {
                            Async.main {
                                self.dismissProgressDialog {
                                    print("success = \(success?.message ?? "")")
                                    self.view.makeToast(success?.message ?? "")
                                    self.socketHelper.emit(event: "on_name_changed", data: ["from_id": AppInstance.instance.sessionId ?? ""])
                                    self.socketHelper.emit(event: "on_avatar_changed", data: ["from_id": AppInstance.instance.sessionId ?? ""])
                                    AppInstance.instance.fetchUserProfile()
                                    self.navigationController?.popViewController(animated: true)
                                }
                            }
                        } 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: RelationshipAlertVCDelegate Methods
extension EditProfileVC: RelationshipAlertVCDelegate {
    
    func handleRelationshipTap(relationship_id: String, relationship: String) {
        self.relationshipTextField.text = relationship
        self.relationship_id = relationship_id
    }
    
}
