//
//  StorySeenUserListVC.swift
//  WoWonder
//
//  Created by UnikApp on 25/02/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import UIKit
import Async
import SDWebImage
import Toast_Swift

protocol StorySeenUserListVCDelegate {
    func handleDismissStorySeenUserListVC(cell: StoryCell)
    func handleStorySeenUserListVCDeleteButtonTap(_ sender: UIButton, cell: StoryCell, story: UserDataStory)
}

class StorySeenUserListVC: BaseVC {

    // MARK: - IBOutlets
    
    @IBOutlet weak var bottomSheetView: UIView!
    @IBOutlet weak var viewedByView: UIView!
    @IBOutlet weak var viewedUserListView: UIView!
    @IBOutlet weak var noViewsLabel: UILabel!
    @IBOutlet weak var viewedByLabel: UILabel!
    @IBOutlet weak var deleteButton: UIButton!
    @IBOutlet weak var shareButton: UIButton!
    @IBOutlet weak var seenUserTableView: UITableView!
    
    // MARK: - Properties
    
    var sheetHeight: CGFloat = 0
    var sheetBackgroundColor: UIColor = .color_fill
    var sheetCornerRadius: CGFloat = 20
    private var hasSetOriginPoint = false
    private var originPoint: CGPoint?
    var seenUsersArray: [UserData] = []
    var story: UserDataStory?
    var delegate: StorySeenUserListVCDelegate?
    var cell = StoryCell()
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.initialConfig()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.getStoryViewAPICall()
    }
    
    override func viewDidLayoutSubviews() {
        if !hasSetOriginPoint {
            hasSetOriginPoint = true
            originPoint = view.frame.origin
        }
    }
    
    // MARK: - Selectors
    
    // Delete Button Action
    @IBAction func deleteButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.dismiss(animated: true) {
            if let story = self.story {
                self.delegate?.handleStorySeenUserListVCDeleteButtonTap(sender, cell: self.cell, story: story)
            }
        }
    }
    
    // Share Button Action
    @IBAction func shareButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let story = self.story {
            var textToShare: [String] = []
            if story.videos?.isEmpty ?? false {
                textToShare = [story.thumbnail ?? ""]
            } else {
                textToShare = [story.videos?.first?.filename ?? ""]
            }
            let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
            activityViewController.popoverPresentationController?.sourceView = self.view
            activityViewController.excludedActivityTypes = [
                UIActivity.ActivityType.airDrop,
                UIActivity.ActivityType.postToFacebook,
                UIActivity.ActivityType.assignToContact,
                UIActivity.ActivityType.mail,
                UIActivity.ActivityType.postToTwitter,
                UIActivity.ActivityType.message,
                UIActivity.ActivityType.postToFlickr,
                UIActivity.ActivityType.postToVimeo,
                UIActivity.ActivityType.init(rawValue: "net.whatsapp.WhatsApp.ShareExtension"),
                UIActivity.ActivityType.init(rawValue: "com.google.Gmail.ShareExtension"),
                UIActivity.ActivityType.init(rawValue: "com.toyopagroup.picaboo.share"),
                UIActivity.ActivityType.init(rawValue: "com.tinyspeck.chatlyio.share")
            ]
            self.present(activityViewController, animated: true, completion: nil)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.sheetHeight = 500 + self.view.safeAreaBottom
        view.frame.size.height = sheetHeight
        view.isUserInteractionEnabled = true
        view.backgroundColor = sheetBackgroundColor
        view.roundCorners(corners: [.topLeft, .topRight], radius: sheetCornerRadius)
        self.setPanGesture()
        self.setUpUI()
    }
    
    // SetUp UI
    func setUpUI() {
        
        
    }
    
    // Set Pan Gesture
    func setPanGesture() {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureRecognizerAction))
        view.addGestureRecognizer(panGesture)
    }
    
    // Gesture Recognizer
    @objc func panGestureRecognizerAction(sender: UIPanGestureRecognizer) {
        let translation = sender.translation(in: view)
        // Not allowing the user to drag the view upward
        guard translation.y >= 0 else { return }
        view.frame.origin = CGPoint(
            x: 0,
            y: self.originPoint!.y + translation.y
        )
        if sender.state == .ended {
            self.dismiss(animated: true) {
                self.delegate?.handleDismissStorySeenUserListVC(cell: self.cell)
            }
        }
    }
    
    private func getStoryViewAPICall() {
        GerStoryViewsManager.instance.getStoryViews(story_id: self.story?.id?.stringValue ?? "" , session_Token: AppInstance.instance._sessionId) { (result)  in
            switch result {
            case .success(let model):
                self.seenUsersArray = model.users ?? []
                self.viewedByLabel.text = "Viewed by \(self.seenUsersArray.count)"
                self.seenUserTableView.reloadData()
            case .failure(let error):
                Async.main {
                    self.dismissProgressDialog {
                        self.view.makeToast(error.localizedDescription)
                    }
                }
                break
            }
        }
    }
}

// MARK: - Extensions

// MARK: TableView Setup
extension StorySeenUserListVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.seenUsersArray.count == 0 {
            self.noViewsLabel.isHidden = false
            self.seenUserTableView.backgroundView = self.noViewsLabel
        } else {
            self.noViewsLabel.isHidden = true
            self.seenUserTableView.backgroundView = nil
        }
        return self.seenUsersArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.seenUserTableView.dequeueReusableCell(withIdentifier: "ViewedUserCell", for: indexPath) as? ViewedUserCell
        configureCell(cell: cell, indexPathForCell: indexPath)
        return cell ?? UITableViewCell()
    }
    
    func configureCell(cell: ViewedUserCell?, indexPathForCell: IndexPath) {
        let objSeenUsers = self.seenUsersArray[indexPathForCell.row]
        cell?.userNameLabel.text = objSeenUsers.name
        let url =  URL(string: objSeenUsers.avatar ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        cell?.userImageView.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            cell?.userImageView.sd_setImage(with: url, placeholderImage: UIImage(named: ""))
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
}
