import UIKit
import SDWebImage
import Async
import WowonderMessengerSDK
import GoogleMobileAds
import FBAudienceNetwork
import IQKeyboardManagerSwift
import Toast_Swift

class SearchRandomVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var emtyView: UIView!
    
    // MARK: - Properties
    
    private var userArray: [UserData] = []
    private let color = UIColor.accent
    var searchFilterModel = SearchFilterModel()
    
    // 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)
    }
    
    // Filter Button Action
    @IBAction func filterButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.dashboard.searchFilterVC() {
            newVC.delegate = self
            newVC.searchFilterModel = self.searchFilterModel
            newVC.modalPresentationStyle = .custom
            newVC.transitioningDelegate = self
            self.present(newVC, animated: true)
        }
    }
    
    @IBAction func searchRandomPressed(_ sender: Any) {
        self.fetchData()
    }
    
    @objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {
        self.searchTextField.resignFirstResponder()
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.tableViewSetup()
        self.textFieldSetup()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))
        tapGesture.cancelsTouchesInView = false
        self.view.addGestureRecognizer(tapGesture)
    }
    
    // TextField Setup
    func textFieldSetup() {
        self.searchTextField.attributedPlaceholder = NSAttributedString(
            string: "Search...",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.searchTextField.delegate = self
    }
    
    // TableView Setup
    func tableViewSetup() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(UINib(resource: R.nib.searchRandomTableCell), forCellReuseIdentifier:  R.reuseIdentifier.searchRandomTableCell.identifier)
        self.tableView.refreshControl = UIRefreshControl()
        self.tableView.refreshControl?.addTarget(self, action: #selector(self.refreshData), for: .valueChanged)
    }
    
    // Refresh Data
    @objc func refreshData() {
        self.fetchData()
    }
    
    private func fetchData() {
        if Connectivity.isConnectedToNetwork() {
            self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
//            self.userArray = []
//            self.tableView.reloadData()
            let sessionToken = AppInstance.instance.sessionId ?? ""
            let search_Key = self.searchTextField.text ?? ""
            Async.background {
                SearchManager.instance.searchUser(session_Token: sessionToken, country: self.searchFilterModel.location, status: self.searchFilterModel.status.lowercased(), verified: self.searchFilterModel.verified.lowercased(), filterByAge: self.searchFilterModel.filterByAge.lowercased(), ageFrom: self.searchFilterModel.ageFrom, ageTo: self.searchFilterModel.ageTo, search_Key: search_Key, gender: self.searchFilterModel.gender.lowercased()) { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("userList = \(success?.users ?? [])")
                                self.userArray = success?.users ?? []
                                if self.userArray.count == 0 {
                                    self.emtyView.isHidden = false
                                    self.tableView.isHidden = true
                                } else {
                                    self.tableView.isHidden = false
                                    self.emtyView.isHidden = true
                                }
                                self.tableView.reloadData()
                                self.tableView.refreshControl?.endRefreshing()
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(sessionError?.errors?.error_text ?? "")
                                print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(serverError?.errors?.error_text ?? "")
                                print("serverError = \(serverError?.errors?.error_text ?? "")")
                            }
                        }
                    } else {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(error?.localizedDescription ?? "")
                                print("error = \(error?.localizedDescription ?? "")")
                            }
                        }
                    }
                }
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
}

// MARK: - Extensions

// MARK: UITextFieldDelegate
extension SearchRandomVC: UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let currentText = textField.text ?? ""
        if currentText != "" {
            self.fetchData()
        } else {
            self.fetchData()
        }
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        let currentText = textField.text ?? ""
        if currentText != "" {
            self.fetchData()
        } else {
            self.fetchData()
        }
    }
    
}

// MARK: TableView Setup
extension SearchRandomVC: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.userArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.searchRandomTableCell.identifier) as! SearchRandomTableCell
        self.setDataUser(cell: cell, indexPath: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let object = userArray[indexPath.row]
        if let newVC = R.storyboard.dashboard.userProfileViewController() {
            newVC.user_id =  object.user_id ?? ""
            newVC.user_data = object
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    func setDataUser(cell: SearchRandomTableCell, indexPath: IndexPath) {
        let obj = self.userArray[indexPath.row]
        let url = URL(string: obj.avatar ?? "")
        cell.delegate = self
        cell.indexPath = indexPath
        let indicator = SDWebImageActivityIndicator.medium
        cell.profileImage.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            cell.profileImage.sd_setImage(with: url, placeholderImage: UIImage(named: ""))
        }
        cell.userNameLabel.text = obj.name
        cell.verifiedImage.isHidden = obj.is_verified == 0
        cell.aboutLabel.text = obj.lastseen?.getLastSeenString(replace: false)
        /*if obj.lastseen_status == "on"{
         cell.statusImageView.image = R.image.icon_online_vector()
         } else {
         cell.statusImageView.image = R.image.icon_offline_vector()
         }*/
        if obj.can_follow == 0 && obj.is_following == 0 && obj.user_id != AppInstance.instance.userProfile?.user_id {
            cell.followButton.isHidden = true
        }
        if obj.follow_privacy == "0" {
            cell.followButton.isHidden = false
        } else if obj.follow_privacy == "1" {
            if (obj.is_following_me == 0) {
                cell.followButton.isHidden = obj.is_following == 0 ? true : false
            } else if (obj.is_following_me == 1) {
                cell.followButton.isHidden = false
            }
        } else {
            cell.followButton.isHidden = false
        }
        if obj.is_following == 1 {
            cell.followButton.backgroundColor = .accent
            cell.followButton.setTitleColor(.gnt_white, for: .normal)
            cell.followButton.setTitle("Following", for: .normal)
        } else {
            cell.followButton.backgroundColor = .clear
            cell.followButton.borderColorV = .accent
            cell.followButton.borderWidthV = 1
            cell.followButton.setTitleColor(.accent, for: .normal)
            cell.followButton.setTitle("Follow", for: .normal)
        }
    }
    
}

// MARK: SearchRandomTableCellDelegate
extension SearchRandomVC: SearchRandomTableCellDelegate {
    
    func handleFollowButtonTap(_ sender: UIButton, indexPath: IndexPath) {
        if userArray.count > indexPath.row {
            let user = self.userArray[indexPath.row]
            if user.is_following == 1 {
                if let messageAlertVC = R.storyboard.popup.messageAlertVC() {
                    messageAlertVC.delegate = self
                    messageAlertVC.messageText = "Are you sure you want to remove this user as your friend?"
                    self.present(messageAlertVC, animated: true, completion: nil)
                    messageAlertVC.confirmButton.tag = indexPath.row
                }
            } else {
                self.followUser(indexPath: indexPath)
            }
        }
    }
    func followUser(indexPath: IndexPath) {
        let user = self.userArray[indexPath.row]
        if Connectivity.isConnectedToNetwork() {
            Async.background {
                FollowingManager.instance.followRequest(user_Id: user.user_id ?? "",  ServerKey: AppInstance.instance._sessionId) { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("userList = \(success?.follow_status ?? "")")
                                self.view.makeToast(success?.follow_status ?? "")
                                if success?.follow_status ?? "" == "followed" {
                                    self.userArray[indexPath.row].is_following = 1
                                } else {
                                    self.userArray[indexPath.row].is_following = 0
                                }
                                self.tableView.reloadRows(at: [indexPath], with: .automatic)
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(sessionError?.errors?.error_text)
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(serverError?.errors?.error_text)
                            }
                        }
                    } else {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(error?.localizedDescription)
                            }
                        }
                    }
                }
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
}

// MARK: MessageAlertVCDelegate Methods
extension SearchRandomVC: MessageAlertVCDelegate {
    
    func messageAlertConfirmButtonPressed(_ sender: UIButton) {
        self.followUser(indexPath: IndexPath(item: sender.tag, section: 0))
    }
    
}

// MARK: SearchFilterVCDelegate Methods
extension SearchRandomVC: SearchFilterVCDelegate {
    
    func handleSearchFilter(searchFilterModel: SearchFilterModel) {
        self.searchFilterModel = searchFilterModel
        self.fetchData()
    }
    
}

// MARK: UIViewControllerTransitioningDelegate Methods
extension SearchRandomVC: UIViewControllerTransitioningDelegate {
    
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        BottomSheetPresentationController(presentedViewController: presented, presenting: presenting)
    }
    
}
