//
//  FindFriendsViewController.swift
//  WoWonder
//
//  Created by UnikApp on 05/12/22.
//  Copyright © 2022 ScriptSun. All rights reserved.
//

import UIKit
import Async
import Toast_Swift
import SDWebImage

class FindFriendsViewController: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var emtyView: UIView!
    
    // MARK: - Properties
    
    private var userArray: [UserData] = []
    private var color = UIColor.accent
    var findFriendFilterModel = FindFriendFilterModel()
    
    // 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) {
        if let newVC = R.storyboard.dashboard.findFriendsFilterVC() {
            newVC.modalPresentationStyle = .custom
            newVC.transitioningDelegate = self
            newVC.delegate = self
            newVC.findFriendFilterModel = self.findFriendFilterModel
            self.present(newVC, animated: true)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.collectionViewSetup()
        self.findFriendFilterModel.gender = "All"
        self.findFriendFilterModel.status = "All"        
        self.findFriendFilterModel.relationship = "All"
        self.fetchData(findFriendFilterModel: self.findFriendFilterModel)
    }
    
    // CollectionView Setup
    func collectionViewSetup() {
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(UINib(resource: R.nib.findFriendsCell), forCellWithReuseIdentifier: R.reuseIdentifier.findFriendsCell.identifier)
        self.collectionView.refreshControl = UIRefreshControl()
        self.collectionView.refreshControl?.addTarget(self, action: #selector(self.refreshData), for: .valueChanged)
    }
    
    // Refresh Data
    @objc func refreshData() {
        self.fetchData(findFriendFilterModel: self.findFriendFilterModel)
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension FindFriendsViewController {
    
    func fetchData(findFriendFilterModel: FindFriendFilterModel) {
        self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
        self.userArray = []
        let sessionToken = AppInstance.instance.sessionId ?? ""
        Async.background {
            SearchManager.instance.searchUserByFilter(session_Token: sessionToken, status: findFriendFilterModel.status.lowercased(), distance: findFriendFilterModel.distance, gender: findFriendFilterModel.gender.lowercased(), relationships: findFriendFilterModel.relationship.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.collectionView.isHidden = true
                                self.emtyView.isHidden = false
                            } else {
                                self.emtyView.isHidden = true
                                self.collectionView.isHidden = false
                            }
                            self.collectionView.refreshControl?.endRefreshing()
                            self.collectionView.reloadData()
                        }
                    }
                } 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 ?? "")")
                        }
                    }
                }
            }
        }
    }
    
    func followUser(indexPath: IndexPath) {
        let user = self.userArray[indexPath.row]
        if Connectivity.isConnectedToNetwork() {
            self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
            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.collectionView.reloadItems(at: [indexPath])
                            }
                        }
                    } 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(NSLocalizedString("Internet Error", comment: "Internet Error"))
            }
        }
    }
    
}

// MARK: Collection View Setup
extension FindFriendsViewController: UICollectionViewDelegate, UICollectionViewDataSource,  UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.userArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "FindFriendsCell", for: indexPath) as! FindFriendsCell
        self.setDataUser(cell: cell, indexPath: indexPath)
        return cell
    }
    
    func setDataUser(cell: FindFriendsCell, indexPath: IndexPath) {
        cell.hideAnimation()
        let obj = self.userArray[indexPath.row]
        let url = URL(string: obj.avatar ?? "")
        cell.delegate = self
        cell.indexPath = indexPath
        let indicator = SDWebImageActivityIndicator.medium
        cell.userImageView.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            cell.userImageView.sd_setImage(with: url, placeholderImage: UIImage(named: ""))
        }
        cell.userNameLabel.text = obj.name
        cell.lastSeenLabel.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)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let flowayout = collectionViewLayout as? UICollectionViewFlowLayout
        let space: CGFloat = (flowayout?.minimumInteritemSpacing ?? 0.0) + (flowayout?.sectionInset.left ?? 0.0) + (flowayout?.sectionInset.right ?? 0.0)
        let size: CGFloat = (collectionView.frame.size.width - space) / 2.0
        return CGSize(width: size, height: 194)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let object = self.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)
        }
    }
    
}

// MARK: FindFriendsCellDelegate Methods
extension FindFriendsViewController: FindFriendsCellDelegate {
    
    func handleFollowButtonTap(_ sender: UIButton, indexPath: IndexPath) {
        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)
        }
    }
    
}

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

// MARK: FilterSearchDelegate Methods
extension FindFriendsViewController: FindFriendsFilterVCDelegate {
    
    func handleFindFriendsFilterData(filterParam: FindFriendFilterModel) {
        self.findFriendFilterModel = filterParam
        self.fetchData(findFriendFilterModel: self.findFriendFilterModel)
    }
    
}

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